Why should I use a virtual destructor in C++?

I noticed in the lesson that a virtual destructor was used in a base class. Why is this necessary?

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.

Run-time Polymorphism

Learn how to write flexible and extensible C++ code using polymorphism, virtual functions, and dynamic casting

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

What is the performance impact of using virtual functions in C++?
The lesson mentions that using virtual functions has performance implications. Can you explain what those are?
What are pure virtual functions in C++?
I came across the term "pure virtual function" while learning about polymorphism. What does it mean and how is it used?
Can virtual functions have default implementations in C++?
Is it possible to provide a default implementation for a virtual function in a base class?
What is the performance impact of using dynamic_cast in C++?
The lesson mentions using dynamic_cast for downcasting. Is there any significant performance overhead associated with dynamic_cast?
How do virtual functions work with multiple inheritance in C++?
If a class inherits from multiple base classes that have virtual functions, how are the virtual function calls resolved?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant