Write a program to show the use of virtual destructor in C++?

Virtual destructor-:

If there are presence of destructor in base and derived class in order to clean up the object, the destructor from both classes should be called.

 

If base class pointer object is pointing to derived class object and if the base class destructor is not virtual and if we delete pointer objects of base class using delete operator, then destructor from base class is only called.

 

So, in order to call destructor from both classes(base and derived), base class destructor should be made virtual.

Output-:

Derived class destructor
base class destructor
Derived class destructor
base class destructor

The difference in the output without the use of  virtual destructor is as below-:

we have removed virtual from the first program to see the difference.

Output-:

base class destructor
Derived class destructor
base class destructor

Be the first to comment

Leave a Reply

Your email address will not be published.


*