When should you use virtual destructors?
Eleanor Gray
Updated on April 13, 2026
.
In this manner, when should a destructor be virtual?
Whenever the class has at least one virtual function. Having virtual functions indicate that a class is meant to act as an interface to derived classes, and when it is, an object of a derived class may be destroyed through a pointer to the base.
Furthermore, what is the purpose of virtual destructor? Virtual Destructor. Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, following program results in undefined behavior.
Beside this, when would you not use a virtual destructor?
In short you should not have a virtual destructor if: 1. You don't have any virtual functions.
If you add a virtual destructor to a class:
- in most (all?)
- the address of the virtual dispatch table is not necessarily valid across processes, which can prevent safely sharing such objects in shared memory.
Can we have virtual destructor?
Any class that is inherited publicly, polymorphic or not, should have a virtual destructor. To put another way, if it can be pointed to by a base class pointer, its base class should have a virtual destructor. If virtual, the derived class destructor gets called, then the base class constructor.
Related Question Answers