CodeBlanks Logo Icon CodeBlanks

Virtual destructor

Learn correct cleanup with virtual destructors.

virtual destructor

When a class has a virtual destructor, deleting through a base pointer also runs the derived class destructor.

Example: Base* b = new Derived();. If ~Base is not virtual, delete b; only calls the Base destructor; the Derived destructor is skipped. This causes memory leaks and undefined behavior. The fix: virtual ~Base() { }. Making the destructor virtual is required for polymorphic classes.

Need for virtual destructor

If a class has at least one virtual method, its destructor must also be virtual. This guarantees proper cleanup in polymorphic usage.

When the destructor is virtual, delete starts from the most derived destructor and goes upward. First ~Derived, then ~Base runs. Resources of both classes are released. This is a fundamental requirement of polymorphic class design in C++.

Practice Proper cleanup with a virtual destructor

Define a Base class with virtual ~Base() body std::cout << "Base gone";. A Derived class inherits with ~Derived() override body std::cout << "Derived gone ";. In main write Base* b = new Derived(); and delete b;.

Starter code

main.cpp
#include <iostream>

// Define Base and Derived classes here

int main() {
    // Create a Derived via Base* and delete it
    return 0;
}

Sample solution

main.cpp
#include <iostream>

class Base {
public:
    virtual ~Base() { std::cout << "Base gone"; }
};

class Derived : public Base {
public:
    ~Derived() override { std::cout << "Derived gone "; }
};

int main() {
    Base* b = new Derived();
    delete b;
    return 0;
}

Expected output

Derived gone Base gone

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the virtual destructor declaration

Question
class Base { public: virtual ____() { } };
Answer
class Base { public: virtual ~Base() { } };

Explanation: ~Base is the destructor name; virtual makes it virtual.

2 When is a virtual destructor required?

main.cpp
Base* b = new Derived();
delete b;
  • Only in a single class
  • When deleting via a base pointer Correct answer
  • Never
  • Only when using a struct

Explanation: A virtual destructor is needed to clean up the derived part on base-pointer delete.

3 Match each piece to its role

Term Meaning
virtual ~Base Virtual destructor
delete b Cleanup call
~Derived Derived destructor
Base* Base pointer

All lessons in Intermediate