1

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?

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
Guodong Hu
  • 303
  • 1
  • 2
  • 11

1 Answers1

3
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.

Sid S
  • 6,037
  • 2
  • 18
  • 24
  • I thought the temporary object was created by the defaul constructor, so I added "cout << "Construct object with defaul constructor." << endl;" in the defalt constructor function. But there still no information about the constructor in the output. So which constructor it uses to create the temporary object? Thank you~ – Guodong Hu Mar 28 '18 at 06:37
  • @LeoHu, that's because the default copy constructor is used. Implement a copy constructor, and it will be called. – Sid S Mar 28 '18 at 20:25