Reputation: 317
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.
Upvotes: 0
Views: 72
Reputation: 13946
test o3;
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.
test passByref_returnByVal(test& obj) {....}
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 is test
(as opposed to test&
or test*
).
Finally, because o3
already exists courtesy of the
test o3;
declaration, the assignment operator is called to assign the return value of passByref_returnByVal
to the already-existing o3
.
So the copy constructor call is happening in passByref_returnByVal
, not in your operator=
.
Upvotes: 1