Using a virtual destructor in a base class is important when dealing with polymorphism and inheritance. When you have a pointer or reference to a base class, but the actual object is an instance of a derived class, a virtual destructor ensures that the correct destructor is called during object destruction.
Consider the following example:
#include <iostream>
class Monster {
public:
~Monster() { // Not Virtual
std::cout << "Monster destroyed\n"; }
};
class Dragon : public Monster {
public:
~Dragon() {
std::cout << "Dragon destroyed\n"; }
};
int main() {
Monster* ptr = new Dragon();
delete ptr;
}
Monster destroyed
In this case, only the base class destructor is called, even though the actual object is a Dragon
. This can lead to resource leaks or undefined behavior if the derived class has its own cleanup logic.
By making the base class destructor virtual, the correct destructor will be called:
#include <iostream>
class Monster {
public:
virtual ~Monster() { // Virtual
std::cout << "Monster destroyed\n"; }
};
class Dragon : public Monster {
public:
~Dragon() {
std::cout << "Dragon destroyed\n"; }
};
int main() {
Monster* ptr = new Dragon();
delete ptr;
}
Dragon destroyed
Monster destroyed
Now, both the Dragon
and Monster
destructors are called in the correct order.
Remember, if a class has at least one virtual function, it's a good practice to make the destructor virtual as well. This ensures proper cleanup and prevents potential memory leaks when dealing with polymorphic objects.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to write flexible and extensible C++ code using polymorphism, virtual functions, and dynamic casting