silent
silent

Reputation: 2924

base destructor called twice after derived object?

hey there, why is the base destructor called twice at the end of this program?

#include <iostream>
using namespace std;

class B{
public:
  B(){
    cout << "BC" << endl; x = 0;
  }
  virtual ~B(){
    cout << "BD" << endl;
  }
  void f(){
    cout << "BF" << endl;
  }
  virtual void g(){
    cout << "BG" << endl;
  }
private:
  int x;
};

class D: public B{
public:
  D(){
    cout << "dc" << endl; y = 0;
  }
  virtual ~D(){
    cout << "dd" << endl;
  }
  void f(){
    cout << "df" << endl;
  }
  virtual void g(){
    cout << "dg" << endl;
  }
private:
  int y;
};

int main(){
  B b, * bp = &b;
  D d, * dp = &d;
  bp->f();
  bp->g();
  bp = dp;
  bp->f();
  bp->g();
}

Upvotes: 0

Views: 1226

Answers (2)

M. Williams
M. Williams

Reputation: 4985

Destructors are called in order, as if they were unwinding the effects of the corresponding constructors. So, first the destructors of the derived objects, then the destructors of the base objects. And making the destructors virtual doesn't have any impact on calling / not calling the base class destructor.

Also to mention, your example could be simplified this way (this code also results in calling the base destructor twice and the derived destructor once):

struct A {
   ~A() {
      // ...
   }
};

struct B: A {
   ~B() {
      // ...
   }
};

int main() {
   A a;
   B b;
}

Upvotes: 3

Artyom
Artyom

Reputation: 31271

Once it is called for b and once for d

Note when destructor of D called it is automatically calls the destructor of B it is different from ordinary virtual functions. where you need explicitly call base class function to use it.

Upvotes: 2

Related Questions