C/C++沉思-----多态时一定要将父类(基类)的析构函数定义为虚函数

先来看一段代码:

//test.cpp
#include <iostream>
using namespace std;

class father
{
public:
	father()
	{
		mPtr = new int;
	}

	~father()
	{
		delete mPtr;
		cout << "father Destruction......" << endl;
	}

private:
	int *mPtr;
};


class son:public father
{
public:
	son()
	{
		mStr = new long;
	}

	~son()
	{
		delete mStr;
		cout << "son Destruction......" << endl;
	}

private:
	long *mStr;
};


int main()
{
	father *p = new son;
	delete p;
	return 0;
}


程序运行截图:

从程序的运行结果来看,程序最后只释放了父类的内存,子类的内存并没有释放。则这段程序产生了内存泄露。那是什么原因导致的呢?

main函数中new出来的是子类son的对象,采用一个父类father的指针来接收,故在析构的时候,编译器因为只知道这个指针是父类的,所以只将父类部分的内存析构了,而不会去析构子类的内存,就造成了内存泄露,那么如何避免这种情况的产生呢?

将父类的析构函数改为虚函数,就可以避免这种情况。

//test.cpp
#include <iostream>
using namespace std;

class father
{
public:
	father()
	{
		mPtr = new int;
	}

	virtual~father()
	{
		delete mPtr;
		cout << "father Destruction......" << endl;
	}

private:
	int *mPtr;
};


class son:public father
{
public:
	son()
	{
		mStr = new long;
	}

	~son()
	{
		delete mStr;
		cout << "son Destruction......" << endl;
	}

private:
	long *mStr;
};


int main()
{
	father *p = new son;
	delete p;
	return 0;
}


程序运行截图:

从程序的运行结果可以看出,父类和子类的内存都被析构了。所以在使用多态时一定要将父类的析构函数定义成虚函数,从而避免内存泄露。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值