虚析构函数
基类的析构函数为什么要定义为虚函数?
基类指针指向派生类对象实现多态,如果基类的析构函数没有定义成虚函数,在删除基类的指针时,只会调用基类析构函数,而不会调用派生类的析构函数,那么派生类的成员就得不到释放,内存释放不完全导致内存泄露。

#include <iostream> using namespace std; class Base { public: Base() { cout << "Base()" << endl; } // 如果~Base()没有定义为虚析构函数,输出将没有"~Driver" virtual ~Base() { cout << "~Base()" << endl; } }; class Driver : public Base { public: Driver() { cout << "Driver()" << endl; } ~Driver() { cout << "~Driver()" << endl; } }; int main(int argc, char *argv[]) { Base *p = new Driver; delete p; return 1; } 输出: Base() Driver() ~Driver() ~Base()
浙公网安备 33010602011771号