0

I understand that the order of calling the destructor is in the reverse order of creation of the objects.

However in the following code I don't understand why the destructor for C(1) and C(2) get called immediately after their constructor.

Also what is the difference between statements: C(2) and C c3(3). The second one is an object initialized with value 3. What is the interpretation of C(2)?

#include <iostream>

class C {
public:
  C(int i)
  {   j = i;
      std::cout << "constructor called for "<<j << std::endl;;
    }
  ~C()
  { std::cout << "destructor called for "<<j<< std::endl;; }

private:
  int j;
};

int main() {
  C(1);
  C(2);

  C c3(3);
  C c4(4);
}

The output of the code is:

constructor called for 1
destructor called for 1
constructor called for 2
destructor called for 2
constructor called for 3
constructor called for 4
destructor called for 4
destructor called for 3
Jason
  • 36,170
  • 5
  • 26
  • 60
user27665
  • 673
  • 7
  • 27

1 Answers1

8

C(1); is a statement containing an expression that creates a temporary of type C, constructed from the argument 1. The temporary is not named - there is no variable name, and no way to refer to that object after the statement finishes executing - so the temporary object's destructor runs immediately after the statement.

That contrasts with C c3(3);, which is a variable definition for the variable named c3. It remains in scope until the end of the enclosing scope, which in this case is the function scope. Because of that, the c4 constructor and destructor run before c3's destructor.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252