in C++: Why should the destructor of base classes 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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With