class test
{
public:
int data;
test(int var = 0):data(var){cout<<"constructor"<<endl;}
~test(){ cout<<"destructor"<<endl; }
test(const test& var)
{
cout<<"copy constructor"<<endl;
this->data = var.data;
}
test& operator=( const test& var)
{
cout<<"assignment op"<<endl;
this->data = var.data;
return *this;
}
};
test passByref_returnByVal(test& obj)
{
return obj;
}
int main()
{
test o1(5);
test o2 = passByref_returnByVal(o1);
cout<<"=========================="<<endl;
test o3;
o3 = passByref_returnByVal(o1);
}
Output:
constructor
copy constructor
constructor
copy constructor
assignment op
destructor
In the given example , object o2 is directly copy constructed without using any temporaries.
But in the second case where i want o3 to be assigned the return value of the function, first a temporary is created using the copy constructor and then assignment operator is called for value assignment.
My question is what was the need for this temporary as my assignment operator takes reference. I found related questions but they didnt answer this.
will cause a call to the constructor to create the object. C++ isn’t Java where an object type declaration only declares a references but doesn’t instantiate an object.
causes the copy constructor call because when inside of it you do
return obj;the compiler needs to create a temporary object because the return type of that function istest(as opposed totest&ortest*).Finally, because
o3already exists courtesy of thedeclaration, the assignment operator is called to assign the return value of
passByref_returnByValto the already-existingo3.So the copy constructor call is happening in
passByref_returnByVal, not in youroperator=.