c++ - virtual destructor

本文详细解释了虚拟析构函数的概念及其在C++中的使用方式。通过具体的代码示例展示了如何正确声明和使用虚拟析构函数,以确保派生类的析构函数能够在删除基类指针时被调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

As we all know that virtual destructor is an essential part of object lifecycle management. so without further adieu, let first see the examples. 

 

 

class Query
{
protected:
	virtual  ~Query();
};

class NotQuery : public Query
{
public :
	virtual ~NotQuery();
};

 

it complies with the pattern of the virutal function and about inheritance, where you declared the functions that are supposed to be changed as protected section, and also, you make the destructor as virual so that you can call the appropriate destructor based on the real object that is pointed by the pointer or reference.

 

 

Now, let's see the example on how to use the virtual destructor based on what we already have now. 

 

#include "virtual_destructor.h"


void demo_virtual_constructor()
{
	Query *pq = new NotQuery();
	// illegal , destructor is protected
	delete pq;
}

 

now we see that there is error with the code above. 

 

 

Now let'se see a revised version. 

 

class Query1
{
public:
	virtual ~Query1();
};

class NotQuery1 : public Query1
{
public:
	virtual ~NotQuery1();
};
 

and with this , the code will works file. 

 

* As a general rule of thumb, we recommend that the root base clas of a class hierarchy declaring one or more virtual destructors virtual as well.
* However, unlike the base class constructor, the base destructor, in general, should not be made protected.
*/
void demo_virtual_constructor1()
{
	Query1 *pq = new NotQuery1();
	delete pq;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值