C++中虚析构函数的作用

在C++编程中,一般基类的析构函数设置为虚析构函数。这么做的目的是什么?下面通过例子来说明:

#include <iostream>
using namespace std;

//基类
class base_class
{
public:
	base_class(){};	//构造函数
	virtual ~base_class(){};	//虚析构函数
//	~base_class(){};	
	virtual void test(){ cout << "This is a test in the base class!\n" << endl; };
};

//派生类
class derived_class: public base_class
{
public:
	derived_class(){};
	~derived_class(){ cout << "This is the output from the destructor of derived class!" << endl;};

	void test(){ cout << "This is a test in the derived class!\n" << endl;};
};

//主函数
int main()
{
	base_class *p = new derived_class;
	p->test();
	delete p;

	return 0;
}

当把基类中的析构函数改为非虚函数时,其输出为:



当把基类中的析构函数改为虚函数时,则其输出为:


从以上对比可以看出,若基类没有使用虚析构函数时,则派生类的析构根本没有被调用。
而我们从C++的语法知识可以,析构函数的作用是释放内存资源,因此若析构函数没被调用,则会造成内存泄露,

因此,可以虚析构函数的作用做是为了当用一个基类的指针删除一个派生类的对象时,派生类的析构函数会被调用。 

当然,并不是要把所有类的析构函数都写成虚函数。因为当类里面有虚函数的时候,编译器会给类添加一个虚函数表,
里面来存放虚函数指针,这样就会增加类的存储空间。所以,只有当一个类被用来作为基类的时候,才把析构函数写成虚函数。

改写自博客:http://blog.csdn.net/starlee/article/details/619827

你可能感兴趣的:(C++中虚析构函数的作用)