Run-time Polymorphism

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?

Abstract art representing computer programming

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.

This Question is from the Lesson:

Run-time Polymorphism

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Run-time Polymorphism

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved