C++ 析构函数 为何一般定义为虚函数

C++ 析构函数 为何一般定义为虚函数,例子:

#include <iostream>
using namespace std;

class Animal
{
public:
	Animal()
	{
		cout << "Animal::Animal() is called" << endl;
	};
	virtual ~Animal()
	{
		cout << "Animal::~Animal() is called" << endl;
	}
	virtual void eat()
	 { 
	 	cout << "Animal::eat() is called" << endl;
	 }
	virtual void walk()
	{ 
	 	cout << "Animal::walk() is called" << endl;
	}
	/* data */
};
class Dog : public Animal
{
public:
	Dog(int w,int h)
	{
		cout << "Dog::Dog() is called" << endl;
		this->weight=w;
		this->height=h;
	}
	virtual ~Dog()
	{
		cout << "Dog::~Dog() is called" << endl;
	}
	int weight;
	int height;
	void eat()
	{
		cout<<"i eat meat"<<endl;
	}
	void walk()
	{
		cout<<"run"<<endl;
	}
	/* data */
};
 int main(int argc, char const *argv[])
{
	/* code */
	Animal *ani= new Dog(12,23);
	Dog *dog=new Dog(23,34);
	ani->eat();
	ani->walk();
	dog->eat();
	dog->walk();
	delete ani;
	//delete dog;
	return 0;
}
如果基类没有定义为虚函数,则delete ani的时候,仅仅调用了父类的析构函数,子类的没有调用,如果在父类和子类的构造函数中都有动态内存分配,那么就会存在内存泄漏的问题。一般析构函数最好都写成虚函数,尤其是父类。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值