Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the destructor of base classes be virtual?

in C++: Why should the destructor of base classes be virtual?

like image 709
Luke Avatar asked May 03 '11 17:05

Luke


People also ask

When should destructor be virtual?

In particular, here's when you need to make your destructor virtual: if someone will derive from your class, and if someone will say new Derived, where Derived is derived from your class, and if someone will say delete p, where the actual object's type is Derived but the pointer p's type is your class.

What is the purpose of virtual destructor?

A virtual destructor is used to free up the memory space allocated by the derived class object or instance while deleting instances of the derived class using a base class pointer object.

Should a class destructor always be virtual?

You should have a virtual destructor if your class is intended as a base-class, in particular if it may be created/destroyed by some other entity than the code that knows what type it is at creation, then you need a virtual destructor. If you are not sure, use virtual destructor.

Should base class destructor be pure virtual?

It is must to provide a function body for pure virtual destructor as derived class's destructor is called first before the base class destructor, so if we do not provide a function body, it will find out nothing to be called during object destruction and error will occur.


Video Answer


1 Answers

They dont have to be virtual unless you are using polymorphism. If you do use polymorphism they need to be virtual so that the destructors of inherited classes are guaranteed to be called, so inherited classes can do their clean up.

like image 185
ralphtheninja Avatar answered Oct 23 '22 13:10

ralphtheninja