Virtual Destructors in C++

Virtual Destructors

Virtual destructors are used to release the memory occupied by the parent as well as child class object. If normal destructors are used then the obtained behavior may be different than the required one.

To understand the behavior of virtual destructors, let us have a look on the following code and its out.

virtual destructors

At line number 25 a pointer object of Person class refers to the object of its child Student class. At line 26 the destructor is called. The intention to call the destructor here is to call the destructor of Student class but it never happens and the output of the above code is as below which shows that the destructor of Person class is called instead of Student class.

destructor of Person class

In order to call the destructor of child as well as parent class, we need to declare the destructors defined in parent class as virtual as shown in the following code.

parent class as virtual

As we can see at line 8, the destructor is declared as virtual. This will allow to call the destructors of both parent and child classes as shown in the figure below.

destructors of both parent and child classes

More Related Articles For You

    C++ Tutorial

    C++ Quizzes