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.
2/4/2018 6:49:00 PMBoris Sos
3 AnswersNew Answer
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.
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.
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.