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 .
Arunmu
source share