#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base(){cout<<"Base"<<endl;}
};
class Derived:public Base
{
public:
~Derived(){cout<<"Derived"<<endl;}
};
int main()
{
Base *base = new Derived;
delete base;
return 0;
}
该程序的运行结果:
Derived
Base
再看下列程序
#include <iostream>
using namespace std;
class Base
{
public:
~Base(){cout<<"Base"<<endl;}
};
class Derived:public Base
{
public:
~Derived(){cout<<"Derived"<<endl;}
};
int main()
{
Base *base = new Derived;
delete base;
return 0;
}
其运行结果是:
Base
也就是说,当基类中析构函数是虚函数时,如果基类指针指向派生类对象,当销毁派生类对象时,就会先调用派生类的析构函数,然后再调用基类的析构函数。但如果基类析构函数没有使用virtual,即如果不是虚析构函数,那么当销毁派生类时,它只会释放Derived中Base部分指向的内存,但不会释放新的类成员指向的内存。
通常要给基类提供一个虚析构函数,即使它并不需要析构函数。