Consider the following scenario
class Integer
{
long long n;
public:
Integer(long long i):n(i){}
Integer(){cout<<"constructor";}
void print()
{
cout<<n<<endl;
}
Integer(const Integer &a){cout<<"copy constructor"<<" "<<a.n<<endl;}
Integer operator+(Integer b);
};
Integer Integer:: operator+(Integer b)
{
this->n = this->n + b.n;
return *this;
}
int main()
{
// your code goes here
Integer a(5);
Integer b(6);
Integer c(a+b);//line 1
return 0;
}
If a+b
was temporary then i understand that copy constructor would not be called. But a+b
does not return a temporary.
The output i get is
copy constructor 6 //this is because Integer object is passed as value to operator+
copy constructor -5232903157125162015 //this is when object is returned by value from operator+
I think there should be one more call when a+b
is used to initialize c
. Most of the related questions have to do with return value optimization but i
can't relate RVO to this.