Reputation: 193
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
Upvotes: 10
Views: 4203
Reputation: 6901
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
.
Upvotes: 10