父类对象的指针指向子类对象时,如果释放指针对应的对象 则只会调用父类对应的析构函数。这时只要在父类的析构函数上 加上一个virtual则调用的析构函数 是子类的,子类析构函数的调用必然触发父类析构函数的调用。
include
using namespace std;
class Parent{
public:
Parent(){
cout << “Parent()” << endl;
}
virtual ~Parent(){
cout << “~Parent()” << endl;
}
virtual void show(){
cout << “show()” << endl;
}
};
class Child:public Parent{
public:
Child(){
cout << “Child()” << endl;
}
~Child(){
cout << “~Child()” << endl;
}
};
int main(){
Parent *pc=new Child();
delete pc;
}