星期四, 5月 03, 2007

星期三, 5月 02, 2007

C++ destructor與virtual destructor

非virtual destructor

class Base{
public: ~Base(){ cout << "base destructor" << endl; }
};

class Derived: public Base{
public: ~Derived(){ cout << "derived constructor" << endl; }
};

void main (int argc, _TCHAR* argv[])
{
{
Derived d;
}
cout << "=========" << endl;
Base *b = new Derived;
delete b;
}

執行結果

derived constructor
base destructor
=========
base destructor


virtual destructor

class Base{
public: virtual ~Base(){ cout << "base destructor" << endl; }
};

class Derived: public Base{
public: ~Derived(){ cout << "derived constructor" << endl; }
};

void main (int argc, _TCHAR* argv[])
{
{
Derived d;
}
cout << "=========" << endl;
Base *b = new Derived;
delete b;
}

執行結果

derived constructor
base destructor
=========
derived constructor
base destructor