1、虚析构函数的作用:避免内存泄漏。
使用虚析构函数在删除指向子类对象的基类指针时,可以调用子类的析构函数使子类占用的堆内存释放,从而防止内存泄漏。
2、使用总结
(1)在基类的析构函数前加上virtual关键字,那么就是虚析构函数。
(2)当基类中的析构函数声明为虚析构函数时,派生类开始从基类继承。
(3)基类的指针指向派生类的对象时,delete基类的指针时,先调用派生类的析构函数,再调用基类中的析构函数。
#include <iostream>
using namespace std;
///基类
class Base{
public:
Base(){};
virtual ~Base(){ //1、定义虚析构函数
cout << "delete Base\n";
};
virtual void DoSomething(){
cout << "Do Something in class Base!\n";
};
};
///派生类
class Derived: public Base{ //2、子类继承
public:
Derived(){};
~Derived(){
cout << "delete Derived\n";
};
void DoSomething(){
cout << "Do Something in Derived\n";
};
};
int main(){
Base *b = new Derived; //3、基类指针指向子类
b->DoSomething();
delete b;
return 0;
}