Why is the output 2020?

Viewed 201

I have the following code:

#include <iostream>
using namespace std;

class Foo {
   int data;
public:
   Foo(int d = 0) {
      data = d;
   }

   ~Foo() {
      cout << data;
   }
};

int main() {
   Foo a;
   a = 20;
   return 0;
}

The output of this code is 2020. I think what happens is, a temporary object a is created. Once the assignment operator is used to assign a the value of 20, the destructor is called and a 20 is printed. Then the main function reaches the return and the destructor is called a second time, printing 20 again.

Am I right?

1 Answers

You are right. Actually modify your code as follows can show the logic of the code more clearly.

#include <iostream>
using namespace std;

class Foo {
   int data;
public:
   Foo(int d = 0) {
      cout << "call constructor!" << endl;
      data = d;
   }

   ~Foo() {
      cout << data << endl;
   }
};

int main() {
   Foo a; // Foo::Foo(int d = 0) is called which yields the first line of output
   a = 20; // is equal to follows
   
   // 1. a temporary object is constructed which yields the second line of output
   Foo tmp(20);
   // 2. since you do not provide operator= member function,
   // the default one is generated the compiler
   // and a member-wise copy is performed
   a.operator=(&tmp);  
   // after this copy assignment, a.data == 20
   // 3. tmp is destroyed which yields the third line of output
   tmp.~Foo();
   // 4. right before the program exits, a is destroyed which yields the last line of output
   a.~Foo();

   return 0;
}

The output is:

call constructor!

call constructor!

20

20

Related