Search code examples
c++destructortemporary-objectscopy-elision

Why there is no temporary object when returning an object through the constructor?


I'm trying to figure out what exactly happens when returning an object through the constructor(conversion function).

Stonewt::Stonewt(const Stonewt & obj1) {
    cout << "Copy constructor shows up." << endl;
}

Stonewt::Stonewt(double lbs) {
    cout << "Construct object in lbs." << endl;
}

Stonewt::~Stonewt() {
    cout << "Deconstruct object." << endl;
}

Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2) {
    double pounds_tmp = obj1.pounds - obj2.pounds;
    return Stonewt(pounds_tmp);
}

int main() {
    Stonewt incognito = 275;
    Stonewt wolfe(285.7);

    incognito = wolfe - incognito;
    cout << incognito << endl;
    return 0;
}

Output:
Construct object in lbs.
Construct object in lbs.

Construct object in lbs.
Deconstruct object.
10.7 pounds

Deconstruct object.
Deconstruct object.

So My Question is:

Why there is no copy constructor (no temporary object) when returning an object through the constructor?


Solution

  • Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2)
    {
        ...
        return obj1;
    }
    

     

       incognito = incognito - wolfe;
    

    Your operator - () is returning a copy of incognito, which you then assign to incognito. The copy is then destroyed.