Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using operator int() instead of operator+

I'm trying to understand why the operator int() is invoked instead of the defined operator+

class D {
    public:
        int x;
        D(){cout<<"default D\n";}
        D(int i){ cout<<"int Ctor D\n";x=i;}
        D operator+(D& ot){ cout<<"OP+\n"; return D(x+ot.x);}
        operator int(){cout<<"operator int\n";return x;}
        ~D(){cout<<"D Dtor "<<x<<"\n";}
};

void main()
{
    cout<<D(1)+D(2)<<"\n";
    system("pause");
}

my output is:

int Ctor D
int Ctor D
operator int
operator int
3
D Dtor 2
D Dtor 1
like image 322
Netap Avatar asked Jul 28 '16 06:07

Netap


People also ask

What does operator int () mean?

operator int() is a conversion operator, which allows this class to be used in place of an int . If an object of this type is used in a place where an int (or other numerical type) is expected, then this code will be used to get a value of the correct type.

What does |= mean in C?

The ' |= ' symbol is the bitwise OR assignment operator.

How do you overload int?

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. User-defined conversions do not take parameters, as there is no way to pass arguments to them.

How do you declare an operator function?

You declare an operator function with the keyword operator preceding the operator. Overloaded operators are distinct from overloaded functions, but like overloaded functions, they are distinguished by the number and types of operands used with the operator. Consider the standard + (plus) operator.


1 Answers

Your expression D(1)+D(2) involves temporary objects. So you have to change you signature of operator+ to take by const-ref

#include <iostream>
using namespace std;

class D {
    public:
        int x;
        D(){cout<<"default D\n";}
        D(int i){ cout<<"int Ctor D\n";x=i;}
        // Take by const - reference
        D operator+(const D& ot){ cout<<"OP+\n"; return D(x+ot.x);}
        operator int(){cout<<"operator int\n";return x;}
        ~D(){cout<<"D Dtor "<<x<<"\n";}
};

int main()
{
    cout<<D(1)+D(2)<<"\n";
}

It prints:

int Ctor D
int Ctor D
OP+
int Ctor D
operator int
3
D Dtor 3
D Dtor 2
D Dtor 1

The operator int is invoked while finding the correct overload for printing it out to cout.

like image 97
Arunmu Avatar answered Oct 11 '22 19:10

Arunmu