c++基类析构函数虚化的目的:
当基类的析构函数没有虚化时,用基类指针指向派生类对象,在进行程序执行完毕后进行销毁时,只能够销毁掉基类指针映射的基类部分,不能够将派生类完全对象销毁,将造成内容泄露。所有将基类析构函数进行虚化,在delete指向派生类对象的指针时,将按照与调用构造器的相反的顺序正确调用析构函数,确保销毁工作的进行。
不将析构函数虚化时:
#include<iostream>
using namespace std;
class Base{
public :
Base(){
cout<<"Base construction"<<endl;
}
virtual void fun(){
cout<<"Base fun"<<endl;
}
~ Base(){
cout<<"Base destruction"<<endl;
}
};
class Derived :public Base{
public :
Derived(){
cout<<"Derived construction"<<endl;
}
void fun(){
cout<<"Derived fun"<<endl;
}
~ Derived(){
cout<<"Derived destruction"<<endl;
}
};
int main(void){
Base * p=new Derived ();
p->fun();
delete p;
return 0;
}
对应执行:
将基类析构函数虚化:
#include<iostream>
using namespace std;
class Base{
public :
Base(){
cout<<"Base construction"<<endl;
}
virtual void fun(){
cout<<"Base fun"<<endl;
}
virtual ~ Base(){
cout<<"Base destruction"<<endl;
}
};
class Derived :public Base{
public :
Derived(){
cout<<"Derived construction"<<endl;
}
void fun(){
cout<<"Derived fun"<<endl;
}
~ Derived(){
cout<<"Derived destruction"<<endl;
}
};
int main(void){
Base * p=new Derived ();
p->fun();
delete p;
return 0;
}
对应执行: