Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output 2020?

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?

like image 901
elmarki Avatar asked Apr 19 '21 00:04

elmarki


People also ask

Has manufacturing output increased?

Manufacturing output increased 0.8% last month after a similar gain in March, the Federal Reserve said on Tuesday. Economists polled by Reuters had forecast factory production would gain 0.4%. Output jumped 5.8% compared to April 2021.

How much output does the US produce?

In the United States, it represents 12 percent of the nation's output and 18 percent of the world's capacity. In Japan, manufacturing is 19 percent of the country's national output and 10 percent of the world total. Overall, China, the United States, and Japan comprise 48 percent of the world's manufacturing output.


Video Answer


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

like image 88
Lintong He Avatar answered Oct 26 '22 12:10

Lintong He