C++ · Module 9 · Lesson 51 min read

Virtual Destructors & How vtables Work

The bug

perl
class Base { public: ~Base(); };            // NOT virtual
class Derived : public Base { std::vector<int> data; };

Base* p = new Derived;
delete p;     // ❌ undefined behaviour: only ~Base runs, Derived's members may leak

The same applies to std::unique_ptr<Base> holding a Derived.

The fix ✅

perl
class Base { public: virtual ~Base() = default; };

Rule: if a class has any virtual function (i.e. it's meant to be used polymorphically), give it a public virtual destructor. (Alternative: a protected non-virtual destructor, so deleting through a Base pointer isn't allowed at all.)

How virtual calls work: the vtable

Most compilers implement virtual functions like this:

  1. Each polymorphic class gets a vtable: a table of pointers to its virtual functions
  2. Each polymorphic object gets a hidden vptr pointing to its class's vtable
  3. p->draw() → follow p's vptr → look up the draw slot → call that function
less
Circle object: [vptr | radius]      Circle vtable: [~Circle, area → Circle::area, draw → Circle::draw]
Square object: [vptr | side]        Square vtable: [~Square, area → Square::area, draw → Square::draw]

Costs of virtual

  • One extra pointer (8 bytes) per object
  • One indirect call (usually tiny, but prevents inlining in hot loops)
  • That's why C++ functions are not virtual by default ("don't pay for what you don't use")

The vptr during construction

While the Base constructor runs, the vptr points to Base's vtable — that's why virtual calls in constructors don't reach the derived override (lesson 9.2).

Checking

std::has_virtual_destructor_v<T> (<type_traits>) and the -Wnon-virtual-dtor / -Wdelete-non-virtual-dtor warnings help catch the bug.

Example

C++
#include <iostream>
#include <memory>

class LeakyBase {
public:
    ~LeakyBase() { std::cout << "  ~LeakyBase\n"; }            // NOT virtual
};
class LeakyDerived : public LeakyBase {
public:
    ~LeakyDerived() { std::cout << "  ~LeakyDerived\n"; }
};

class SafeBase {
public:
    virtual ~SafeBase() { std::cout << "  ~SafeBase\n"; }     // virtual destructor
    virtual void speak() const { std::cout << "  SafeBase speaks\n"; }
};
class SafeDerived : public SafeBase {
public:
    ~SafeDerived() override { std::cout << "  ~SafeDerived\n"; }
    void speak() const override { std::cout << "  SafeDerived speaks\n"; }
};

struct Plain { int x; double y; };
struct WithVirtual { int x; double y; virtual ~WithVirtual() = default; };

int main() {
    std::cout << "Deleting LeakyDerived through LeakyDerived*:\n";
    {
        LeakyDerived* d = new LeakyDerived;
        delete d;                                // fine: the static type is the real type
    }
    // LeakyBase* b = new LeakyDerived; delete b;  // undefined behaviour: ~LeakyDerived would be skipped

    std::cout << "Deleting SafeDerived through SafeBase*:\n";
    std::unique_ptr<SafeBase> s = std::make_unique<SafeDerived>();
    s->speak();
    s.reset();                                   // both destructors run, derived first

    std::cout << "sizeof(Plain) = " << sizeof(Plain)
              << ", sizeof(WithVirtual) = " << sizeof(WithVirtual) << " (extra hidden vptr)\n";
    std::cout << std::boolalpha << "LeakyBase has virtual destructor? "
              << std::has_virtual_destructor_v<LeakyBase> << ", SafeBase? "
              << std::has_virtual_destructor_v<SafeBase> << '\n';
    return 0;
}

/* Output:
Deleting LeakyDerived through LeakyDerived*:
  ~LeakyDerived
  ~LeakyBase
Deleting SafeDerived through SafeBase*:
  SafeDerived speaks
  ~SafeDerived
  ~SafeBase
sizeof(Plain) = 16, sizeof(WithVirtual) = 24 (extra hidden vptr)
LeakyBase has virtual destructor? false, SafeBase? true
*/