Explain the need for "Virtual Destructor".

Questions by suji   answers by suji

Showing Answers 1 - 8 of 8 Answers

In case of inheritance, objects should be destructed exactly the oppossite way of their construction. If virtual keyword is not added before base class destructor declaration, then derived class destrcutor will not at all be called. Hence there will be memory leakage if allocated for derived class members while constrcting the object.

kavs

  • Aug 16th, 2006
 

To call the destruction of objects in the reverse way of their creation,virtual destructor must be used.The order of execution of destructor in an inherited class during a clean up is like this.1. Derived class destructor2. Base class destructor There is one more point to be noted regarding virtual destructor. We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body (at least) for the destructor.

  Was this answer useful?  Yes

jezpops

  • Jul 7th, 2008
 

Virtual destructor is used when deleting an object explicitly using the delete[] keyword. The Virtual destructor ensures that derived classes take on the implicit destructor method. 

  Was this answer useful?  Yes

Virtual destructor makes sure that all derived objects are deleted first before deleting the base class objects. When base class pointer assigned with Derived class objects, the virtual destructor of the base class make sure that it deletes the derived class (child) object before it deletes the base class(parent) object.
Thanks
Niranjan Ambati

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