C++ Virtual Destructors
In C++, a virtual destructor is a destructor that is declared as virtual in a base class. A virtual destructor is used when you have a hierarchy of classes, and you need to ensure that the correct destructor is called when you delete an object of the derived class through a pointer of the base class.
When you delete an object through a pointer to the base class, the destructor of the base class is called, but the destructors of the derived classes are not automatically called. This can lead to memory leaks and other problems, because the resources allocated by the derived class objects are not properly freed.
To ensure that the correct destructor is called for the derived class objects, you should declare the destructor in the base class as virtual. This allows the destructor of the derived class to be called when an object of the derived class is deleted through a pointer of the base class.
Here's an example:
class Animal { public: virtual ~Animal() { std::cout << "Animal destructor." << std::endl; } }; class Dog : public Animal { public: ~Dog() override { std::cout << "Dog destructor." << std::endl; } }; int main() { Animal* a = new Dog(); delete a; }Source:www.theitroad.com
In this example, we have a base class Animal
with a virtual destructor. We also have a derived class Dog
, which overrides the destructor with its own implementation.
In the main()
function, we create an object of type Dog
, but we assign it to a pointer of type Animal
. This allows us to delete the object through the pointer of the base class. When we delete the object, the destructor of the Dog
class is called, because the destructor in the Animal
class is declared as virtual.
Without the virtual destructor, only the destructor of the Animal
class would be called, and the resources allocated by the Dog
object would not be properly freed. This could lead to memory leaks and other problems.