Explain the need for "Virtual Destructor".

Showing Answers 1 - 4 of 4 Answers

Ruth Samuel

  • Aug 30th, 2005
 

When classes are inherited, we need to make the base class destructor virtual ? to make sure when the object is destroyed, all the derived class destructors also called. Otherwise the derived class destructors are not called because the there is compile time binding of the destructor pointer to the base class destructor.  
 

  Was this answer useful?  Yes

Writing Virtual Destructor is not always necessary, though it is a good practice.

Your Destructor MUST be Virtual, specially in cases, when your class deals with objects on heap, i.e. when one or more your class member data are pointers.
Some books also recommend, that Virtual Destructor is member of 3 (Copy Constructor, Assignment Operator & Virtual Destructor).
If any of these 3, are felt to be implemented, you MUST implement other two too.
And the need arises mostly in case of pointer members, or dynamically allocated members.

And, as base class is not aware of any derivation of it (i.e. writer of base class, can not guarantee that the class will be or will not be derived further), so it is his responsibility to write virtual destructor, in case of dynamically allocated member data.
Hence, in case of derivation, when object of derived class goes out of scope (dies), the destructor of Base class is also called, due to being VIRTUAL.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions