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

I am trying to understand why instead of operator+

operator int() is called
 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 conclusion:

 int Ctor D int Ctor D operator int operator int 3 D Dtor 2 D Dtor 1 
+8
c ++ operator-overloading
source share
1 answer

Your expression D(1)+D(2) includes temporary objects. So you need to change your operator+ signature to 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"; } 

He prints:

 int ctor d
 int ctor d
 OP +
 int ctor d
 operator int
 3
 D Dtor 3
 D Dtor 2
 D Dtor 1

operator int is called to find the correct overload to print before cout .

+9
source share

All Articles