Overloading Typecasts
Table of Contents


C++ already knows how to convert between the built-in data types. However, it does not know how to convert any of our user-defined classes.


Example 1

class Cents
    int m_nCents;
    Cents(int nCents=0)
        m_nCents = nCents;
    // Overloaded int cast
    operator int() { return m_nCents; }
    int GetCents() { return m_nCents; }
    void SetCents(int nCents) { m_nCents = nCents; }
int main()
    Cents cCents(7);
    PrintInt(cCents); // print 7
    return 0;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.