+ 1
Overloading of operators
class MyClass { public: int var; MyClass() {} MyClass(int a) : var(a) { } MyClass operator+(MyClass &obj) { MyClass res; res.var= this->var+obj.var; return res; } }; The question is the following. If I understand correctly, we created the example of MyClass called 'res' and it is a local parameter. Meaning, it is supposed to be deleted right after we are back from the body of the function to the main function. So, isn't there a mistake: we try to return the data that is to be deleted.
1 Réponse
+ 3
That would only be the case if you returned a reference or a pointer to that local object, because in that case, the reference/pointer would become empty because of the deletion of the local object, you are correct there.
However, in our case, you return not the original object, but rather a copy of it, which is a new object and therefore not affected by the deletion of the original, local res.