作用:作为基类使用的类应该具有虚析构函数,以保证在删除基类指针(动态分配的对象)时,根据指针实际指向的对象进行适当的析构。
请看下面这段代码;
#include <iostream> class A{ public: A(){ std::cout << "A constructor execute" << std::endl; } ~A(){ std::cout << "A destructor execute" << std::endl; } virtual void doSomething(){ std::cout << "A dosomething" << std::endl; } }; class B : public A { public: B(){ std::cout << "B constructor execute" << std::endl; } ~B(){ std::cout << "B destructor execute" << std::endl; } void doSomething(){ std::cout << "B dosomething" << std::endl; } }; int main(int argc, char** argv) { A *a = new B(); a->doSomething(); delete a; return 0; }执行结果:
可以看到:B的析构函数式没有被执行的,这在平时的编程中是非常危险的。
为了能够正确执行A和B的析构,我们将A的析构函数改为虚析构函数。
#include <iostream> class A{ public: A(){ std::cout << "A constructor execute" << std::endl; } virtual ~A(){ std::cout << "A destructor execute" << std::endl; } virtual void doSomething(){ std::cout << "A dosomething" << std::endl; } }; class B : public A { public: B(){ std::cout << "B constructor execute" << std::endl; } ~B(){ std::cout << "B destructor execute" << std::endl; } void doSomething(){ std::cout << "B dosomething" << std::endl; } }; int main(int argc, char** argv) { A *a = new B(); a->doSomething(); delete a; return 0; }执行结果:
原文地址:http://blog.csdn.net/wangbin_jxust/article/details/40110967