from: http://blog.csdn.net/lwbeyond/article/details/7497294
第一种情况:基类指针指向派生类对象。
- #include <iostream>
- using namespace std;
- class Base{
- public:
- ~Base() {cout<<"~B"<<endl;}
- };
- class Derived:public Base{
- public:
- ~Derived() {cout<<"~D"<<endl;}
- };
- int main (){
- Base *b = new Derived; //注意这里
- delete b;
- }
第二种情况:派生类指针指向派生类对象。
- #include <iostream>
- using namespace std;
- class Base{
- public:
- ~Base() {cout<<"~B"<<endl;}
- };
- class Derived:public Base{
- public:
- ~Derived() {cout<<"~D"<<endl;}
- };
- int main (){
- Derived *d = new Derived; //注意这里
- delete d;
- }
这次基类和派生类都能被析构掉。
第三种情况:基类指针指向派生类对象,但析构函数是virtual 的。
- class Base{
- public:
- virtual ~Base(){cout<<"~B"<<endl;};
- }
- class Derived:public Base{
- public:
- virtual ~Derived(){cout<<"~D"<<endl;};
- }
- void main (){
- Base *b=new Derived();
- delete b;
- }