开发者

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" << 开发者_StackOverflowendl;
  }
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();
}


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜