0

I tried this code:

#include <iostream>
using namespace std;

class A {
public:
A(){cout<<"A();";}
 ~A(){cout<<"~A();";}
};

class B : public A {
public:
B(){cout<<"B();";}
 ~B(){cout<<"~B();";}
};

int main() {
A a =B();
return 0;
}

Output: A();B();~B();~A();~A();

Why is A's destructor invoked 2 times?

Hayt
  • 5,210
  • 30
  • 37
J.Doe
  • 9
  • 1

1 Answers1

5

After you create a temporary object, which is being copied into a (with slicing!) the first destruction starts. A temporary object (B();) is being destructed - first ~B() and then the destructor of its parent class ~A() is called. Then a goes out of scope and its destructor fires.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130