You are here:

C++/C++ - Virtual destructors

Advertisement


Question
Q: When do we use Virtual destructors in c++.
Kindly explain in detail.

Thank you very much for your effort.
Regards,
Subbu.

Answer
Subbu,
  When you have a base and derived classes , the construction of the object of derived is in the following order:
[1] Construction of base (using base class constructor) and then
[2] Construction of derived (using derived class construction)

The destruction, as logical should be in the opposite order.

Now, when you have an object pointer of a base class and you are constructing it as a derived class, you need to destruct it properly as mentioned above. But it is not, normally. When you try to delete a "new'ed as derived" pointer of object of base class, it calls immediately the destructor of the base class (leaving us with the probability of memory leak).

If we declare (we should in all cases), the destructor(s) of base class(es) as virtual, the above anomaly could be avoided.

Please read the article at http://www.codersource.net/cpp_virtual_destructors.html


Regards,
RaiD

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Dharmender Rai

Expertise

I can answer general and system level C/C++ questions.

Experience

I have 5 years of experience in C++.

©2016 About.com. All rights reserved.