原因:
在公有继承中,基类的虚构函数如果不声明成为虚函数,那么销毁派生类时有可能造成资源泄漏
class Base{ public:
Base( ) { };
~Base( ) { };
};
class Derived :public Base{
public:
Derived( ) { };
~Derived( ){ };
};
void main( )
{
Base *p;
p = new Derived;
delete p;
}
这种情况会发生销毁不完全的情况,因为delete p调用的是声明类型(即基类)的析构函数,所以只能销毁基类对象而无法销毁派生类对象。
修改后:
class Base{ public:
Base( ) { };
virtual ~Base( ) { };
};
class Derived :public Base{
public:
Derived( ) { };
~Derived( ){ };
};
void main( )
{
Base *p;
p = new Derived;
delete p;
}
当基类的析构函数声明为虚函数,那么派生类的析构函数也是虚函数,此时调用delete p时发生动态绑定,运行时会根据实际类型调用该对象的虚函数。
当然,并不是要把所有类的析构函数都写成虚函数。只有当一个类是基类(即希望被继承)的时候才需要声明成虚函数,因为虚函数的作用是实现多态,而多态是建立在继承的基础上。单一类不能把析构函数写成虚函数,因为会产生额外的开销,比如虚表的创建和虚指针的定义。