Search

9.10 — Overloading typecasts


In the lesson on type conversion and casting, you learned that C++ allows you to convert one data type to another. The following example shows an int being converted into a double:

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. That’s where overloading the typecast operators comes into play.

Overloading the typecast operators allows us to convert our class into another data type. Take a look at the following class:

This class is pretty simple: it holds some number of cents as an integer, and provides access functions to get and set the number of cents. It also provides a constructor for converting an int into a Cents.

If we can convert an int into a Cents, then doesn’t it also make sense for us to be able to convert a Cents back into an int? In the following example, we have to use GetCents() to convert our Cents variable back into an integer so we can print it using PrintInt():

If we have already written a lot of functions that take integers as parameters, our code will be littered with calls to GetCents(), which makes it more messy than it needs to be.

To make things easier, we’ll overload the int cast, which will allow us to cast our Cents class into an int. The following example shows how this is done:

There are two things to note:
1) To overload the function that casts our class to an int, we write a new function in our class called operator int(). Note that there is a space between the word operator and the type we are casting to.
2) Casting operators do not have a return type. C++ assumes you will be returning the correct type.

Now in our example, we call PrintInt() like this:

The compiler will first note that PrintInt takes an integer parameter. Then it will note that cCents is not an int. Finally, it will look to see if we’ve provided a way to convert a Cents into an int. Since we have, it will call our operator int() function, which returns an int, and the returned int will be passed to PrintInt().

We can now also explicitly cast our Cents variable to an int:

You can overload cast operators for any data type you wish, including your own user-defined data types!

Here’s a new class called Dollars that provides an overloaded Cents cast operator:

This allows us to convert a Dollars object directly into a Cents object! This allows you to do something like this:

Consequently, this program will print the value:

900

which makes sense, since 9 dollars is 900 cents!

9.11 — The copy constructor and overloading the assignment operator
Index
9.9 — Overloading the parenthesis operator

12 comments to 9.10 — Overloading typecasts

  • Zafer

    To convert a Dollar object to a Cents object, Dollar class uses Cents class by returning Cents(m_nDollars * 100). Shouldn’t we declare the Cents class before Dollar to be able to generate a Cents object?

  • Tom

    Hello Alex –

    I think this is a typo:

    I think it should be:

    Correct?

    [ You are correct! It has been fixed. -Alex ]

  • Stuart

    void PrintCents(const Cents& cCents)
    {
    cout << cCents.GetCents();
    }

    int main()
    {
    Dollars cDollars(9);
    cout << PrintCents(cDollars); // cDollars will be cast to a Cents

    return 0;
    }

    Alex, I think the cout << before the PrintCents() function call is a mistake here.

    (Tags didn’t work again. Sorry.)

  • thanks Mr alex
    you did well explanation

    I will translation this lessons to my language

    Best wishes

  • Brooklyn

  • louiskepler

    Hi, its my first time replying on this epic tutorial but here goes:
    I was making a vector class using the IntArray example as a guide, then I decided to make it a template class as spoken about in the template tutorial. My question is, can I make a template typecast operator E.G:
    template
    T operator T()
    {
    return values[0];//just an example to illustrate the idea, this would only work for vectors of type T
    }
    I have tried google to no avail…

  • ikshuvish

    Hi I have a question related to type casting. I am trying to understand a code in which there is a class called X and this has a private member variable unsigned int.
    The type caste code is similar to below.

    unsigned int a;
    X b; (assume b is initiazed)

    a = (unsigned int &)b;

    When do we need such a reference type caste in the code?

    It would be of great help if I can get answer to this at the earliest. Thanks in advance.

  • harikumar

    How does operator conversion functions are identified by the complier

  • harikumar

    class A {
    int x;
    public:
    A()
    {
    x=100;
    }

    A (int i)
    {
    x=i;
    }
    operator int()
    {
    return x;
    };

    /*operator float()
    {
    return y;
    };*/

    A(A &obj)
    {
    x=obj.x;

    }

    A add(A &obj)
    {
    x+=obj.x;
    return *this;//temp;
    }

    A operator +(A & o)
    {
    return this->add(o); //How does operator int() gets invoked here ? . It should be through copy constructor
    }
    A& operator=(A &o)
    {
    //A temp;
    return o;
    }
    };

    int main()
    {
    A obj1;
    A obj2;
    A obj3=obj2+obj1;
    }

  • FuckTheDuck

    you forgot to mention conversion constructors too, it would be appropriate to explain it in this context.
    thanks for the good tutorial

Leave a Comment (Note: put C++ code inside [code][/code] brackets)

  

  

  

2 × two =

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">