FredyR4zox
FredyR4zox

Reputation: 31

C++ operator overloading return

In this code:

RationalNum operator+(const RationalNum& left, const RationalNum& right) {
    RationalNum temp;
    /*code here*/
    return temp;
}

How can it return a RationalNum object if the object is "deleted" from the stack when this function exits?

Upvotes: 2

Views: 224

Answers (1)

SoronelHaetir
SoronelHaetir

Reputation: 15172

It is because the return value is copied (if necessary) before local variables are destroyed. And destroying the returned object is the duty of the calling function.

The returned object is constructed at the point of the return statement but the destruction of locals is left until the end of the block (which comes after the return).

Upvotes: 7

Related Questions