+ 2

Assigning the value and copy constructor

In line MyClass res = op1 + op2; do we call operator= or copy constructor? Other question is what happens to object that is instantiated inside operator+ code? We obviously made two new objects, one is res and the other inside operator+ method, which is later assigned to res variable.

4th Feb 2018, 6:49 PM
Boris Sos
Boris Sos - avatar
3 Answers
0
Regarding first question, a copy constructor is called as you are assigning op1+op2 at the time of declaring the variable res. Had it been MyClass res; res = op1+op2; operator= would have been invoked. The object created inside the operator+ method is a local variable and will go out of scope as soon as it gets assigned to res.
4th Feb 2018, 9:15 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
0
Thanks Ravi. So all other variables declared inside a function dies immediately after function call. Except for variable that is returned as a result, which lives a bit longer, just after it is assigned to some other variable. And I guess that destructor is called on that instance.
5th Feb 2018, 6:03 AM
Boris Sos
Boris Sos - avatar
0
Yes, all the variables which are stored on stack memory (not created using dynamic memory allocation) gets destroyed after the function call. Destructor also gets called.
5th Feb 2018, 10:04 AM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar