DEV Community

Play Button Pause Button
Mahima Bhardwaj
Mahima Bhardwaj

Posted on

Virtual Destructors in C++ | C++ Programming| Destructor in C++|

In C++, a virtual destructor is used to ensure that the destructor of a derived class is called when an object is deleted through a pointer to the base class. This is crucial when dealing with polymorphism, as it allows the appropriate destructor to be invoked for an object of a derived class, ensuring proper resource cleanup and avoiding potential memory leaks.

Why is a Virtual Destructor Necessary?
When you delete an object through a pointer to a base class, C++ will call the base class destructor by default. If the base class destructor is not virtual, only the base class destructor will be called, leading to incomplete cleanup of resources allocated by the derived class. If the destructor is virtual, the destructor of the derived class is also called, allowing for proper cleanup.

Top comments (0)