#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout<<"这是父亲的构造函数"<<endl;
}
virtual ~Base()
{
cout<<"这是父亲的析构函数"<<endl;
}
virtual void DoSomething()
{
cout<<"Do something in class Base!"<<endl;
}
};
class Derived:public Base{
public:
Derived(){
cout<<"这是儿子的构造函数"<<endl;
}
~Derived(){
cout<<"这是儿子的析构函数"<<endl;
}
void DoSomething(){
cout<<"Do something in class Derived!"<<endl;
}
};
int main(){
Derived *pTest1 = new Derived();
pTest1->DoSomething();
delete pTest1;
cout<<endl;
Base *pTest2 = new Derived();
pTest2->DoSomething() ;
delete pTest2;
return 0;
}
结果
要是去掉~Base()析构函数前的virtual关键字,则子类的析构函数不会被调用,这样会造成内存泄漏。