虚析构函数时为了解决基类的指针指向派生类对象,并用基类的指针删除派生类的对象。
class Dad
{
public:
Dad()
{
cout << "Dad constructor" << endl;
}
virtual ~Dad()//父类析构函数声明为virtual
{
cout << "Dad desstructor" << endl;
}
};
class Son :public Dad
{
public:
int* arr;
Son()
{
arr = new int[10];
cout << "Son constructor" << endl;
}
~Son()
{
if (arr != NULL)
{
delete arr;
arr = NULL;
}
cout << "Son destructor" << endl;
}
};
int main()
{
Dad* dad = new Son;//父类指针指向子类对象
dad->~Dad();//调用~Dad(),用基类的指针删除子类对象
system("pause");
return 0;
}