skip to content

In C++, what goes wrong when you delete a derived Reverb object through an Effect* whose destructor is not virtual?

level: juniorimportance: must knowfreq 82%

answer

  1. static type versus dynamic type at delete
  2. the standard's word: undefined
  3. derived destructor and members skipped
  4. one line in the base class
  5. or a protected non-virtual destructor

basics

~20 s

The delete has undefined behaviour. In practice compilers usually call only ~Effect, so ~Reverb and the destructors of Reverb's members never run and whatever they own leaks. Declaring virtual ~Effect() = default in the base fixes it.

solid answer

~40 s

The standard says that deleting an object through a pointer whose static type differs from its dynamic type is **undefined behaviour** unless the static type has a **virtual destructor**. With a non-virtual `~Effect()`, compilers typically emit a direct call to `Effect::~Effect`, so `Reverb::~Reverb` never runs and a member such as a `std::vector<float>` tail buffer is never freed. Because it is undefined, a leak is not even the guaranteed outcome: Apple clang 21 compiles the complete-object destructor of an *abstract* base to a trap instruction, so the same program aborts. The fix is `virtual ~Effect() = default;` in the base: every derived destructor then overrides it, and `delete` or `std::unique_ptr<Effect>` destroys the whole object, derived part first. A base that must never be deleted polymorphically can instead get a `protected` non-virtual destructor.

code

cpp · 18 lines
cpp
#include <cstdio>
#include <vector>

struct Effect {
    virtual void process(float*, int) {}
    ~Effect() { std::puts("~Effect"); }  // not virtual
};

struct Reverb : Effect {
    std::vector<float> tail = std::vector<float>(48000);
    void process(float*, int) override {}
    ~Reverb() { std::puts("~Reverb"); }
};

int main() {
    Effect* e = new Reverb;
    delete e;  // undefined behaviour: ~Effect is not virtual
}

go deeper

for a junior

Recall the rule in one line: a class meant to be deleted through a base pointer gets virtual ~Base() = default, otherwise the derived destructor is skipped.

for a middle

Explain why: delete dispatches on the static type, the standard calls the mismatch undefined behaviour, and once the base destructor is virtual every derived destructor overrides it automatically.

for a senior

Show you would catch it in review and tooling: -Wall's delete warnings, unique_ptr versus shared_ptr behaviour, and why a leak is only the usual symptom of undefined behaviour, not a promise.

for a principal

Frame it as a codebase rule: polymorphic bases get public virtual or protected non-virtual destructors, leaf types are final, and the warnings that enforce this fail the build.

## The rule: delete looks at the static type A **delete-expression** works from the type of the pointer you hand it, its **static type**. When that pointer is an `Effect*` but the object it points to was created as a `Reverb`, the object's **dynamic type** is `Reverb`. The standard's section on `delete` says that in this situation the static type must be a base class of the dynamic type **and must have a virtual destructor, or the behaviour is undefined**. ```cpp struct Effect { virtual void process(float* buf, int n) = 0; ~Effect(); // not virtual }; struct Reverb : Effect { std::vector<float> tail; /* ... */ }; Effect* e = new Reverb; delete e; // undefined behaviour ``` Having other virtual functions does not help. `process()` being virtual makes `Effect` a **polymorphic class**, but the destructor is virtual only if it is declared `virtual` in `Effect` or overrides a virtual destructor in one of `Effect`'s own bases. ## What actually happens without it Undefined behaviour means the standard places no requirement on the result, so any of these can happen: - **The usual outcome:** the compiler calls `Effect::~Effect` directly, as it would for any non-virtual function. `Reverb::~Reverb` never runs, so the destructors of `Reverb`'s members never run either, and the 48,000-sample `tail` buffer leaks along with any file handle or lock the class held. - **The memory release can be wrong too:** `operator delete` may be handed the size of an `Effect` while the allocation was the size of a `Reverb`. - **A trap:** when `Effect` is abstract, no complete `Effect` object can ever exist, so a call to its complete-object destructor can only come from a program with undefined behaviour. Apple clang 21 compiles that destructor to a trap instruction, and the program above stops with a signal instead of leaking. So "it just leaks" is the common symptom, not a guarantee. Treat the delete as a bug, not as a leak to tolerate. ## The fix: one line in the base ```cpp struct Effect { virtual ~Effect() = default; virtual void process(float* buf, int n) = 0; }; ``` Once the base destructor is virtual, the destructor of every class derived from it is virtual too, whether it is user-declared or implicit, and it overrides the base's. `delete e` now dispatches to `Reverb::~Reverb`, which destroys `Reverb`'s members and then calls `Effect::~Effect`, in that order. Writing `~Reverb() override` in the derived class is allowed and documents intent, but it is not required. One side effect belongs to the rules for special members: a **user-declared destructor**, even a defaulted one, stops the compiler from implicitly declaring the move constructor and move assignment, and the implicit copy operations it still generates are deprecated. For a base held through pointers this rarely matters; if you copy or move derived objects by value, default those operations explicitly. ## Smart pointers do not rescue a missing virtual destructor | Owner | What it destroys | Needs a virtual destructor? | |---|---|---| | `delete basePtr` | through the static type | yes | | `std::unique_ptr<Effect>` | calls `delete` on an `Effect*` through `std::default_delete<Effect>` | yes | | `std::shared_ptr<Effect>` made from `std::make_shared<Reverb>()` or from a `Reverb*` | the control block remembers the `Reverb` | no, but do not rely on it | `std::shared_ptr` captures how to destroy the object when it is first created from a `Reverb`, so it happens to call the right destructor. Relying on that is fragile: the same object handed to a `std::unique_ptr<Effect>`, or created through a factory that returns `Effect*`, is back to undefined behaviour. ## When a virtual destructor is the wrong answer 1. **A base never deleted through:** a mixin or an interface the hierarchy uses internally can make its destructor `protected` and non-virtual. Then `delete basePtr` outside the hierarchy is a compile error, while derived classes can still destroy their base part. 2. **A class that is final:** if no class may derive from it, a pointer to it always points to the complete object, so there is nothing to dispatch to; Clang's warning below fires only for non-final classes. 3. **A class with no virtual functions at all:** a value type that is never used as a polymorphic base does not need one; adding it only makes the type polymorphic. ## Let the compiler find them Both major compilers warn at the `delete`: GCC's `-Wdelete-non-virtual-dtor` is enabled by `-Wall`, and Clang reports `-Wdelete-non-abstract-non-virtual-dtor` or `-Wdelete-abstract-non-virtual-dtor` under `-Wall`. Clang even reports the case inside `std::unique_ptr`'s deleter. Keep those warnings on and treat them as errors on code that defines polymorphic bases.

  • Once Effect has a virtual destructor, does Reverb need to declare one too?
    No. The destructor of every class derived from a class with a virtual destructor is itself virtual and overrides it, whether you write it or the compiler declares it implicitly. Writing `~Reverb() override` is legal and documents intent, but the implicit destructor already makes `delete` through `Effect*` destroy the whole `Reverb`.
  • Why does std::shared_ptr<Effect> p = std::make_shared<Reverb>() run ~Reverb even without a virtual destructor?
    Because the control block is created for a `Reverb` and destroys a `Reverb`; converting to `shared_ptr<Effect>` keeps that control block. `std::unique_ptr<Effect>` has no such record: its deleter calls `delete` on an `Effect*`, so it still needs the virtual destructor. Do not design around the `shared_ptr` behaviour.
  • When would you give a base class a protected non-virtual destructor instead?
    When callers should never delete through the base, as with a mixin or an internal interface. A `protected` destructor turns `delete basePtr` into a compile error outside the hierarchy while derived destructors can still destroy the base part, so the dangerous delete cannot be written in the first place.

  • Any virtual function in the base makes its destructor virtual automatically.
  • Without a virtual destructor the program reliably just leaks the derived members.
  • std::unique_ptr<Effect> calls the right destructor even when ~Effect is not virtual.
  • Deleting through a base pointer without a virtual destructor fails to compile.
  • Each derived class must declare its own virtual destructor for delete to work.