c++ - virtual destructor

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;
}
 

你可能感兴趣的:(C++)