base destructor called twice after derived object?

Posted by sil3nt on Stack Overflow See other posts from Stack Overflow or by sil3nt
Published on 2010-06-05T12:50:17Z Indexed on 2010/06/05 12:52 UTC
Read the original article Hit count: 254

Filed under:
|
|
|
|

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

© Stack Overflow or respective owner

Related posts about c++

Related posts about gcc