CKTIS / C++
Using `= default` on a virtual destructor
Declare a public virtual base-class destructor so a derived object can be deleted through a base pointer without writing a destructor body for the base class.
Version: ISO C++23; implementation support may vary
Syntax
struct Base {
virtual ~Base() = default;
};In virtual ~Base() = default;, virtual enables virtual dispatch, while = default explicitly asks the compiler to generate the standard definition of this special member function. The syntax = default; is a function definition, not the default: label in a switch.
The generated destructor still destroys members and base subobjects according to the usual C++ rules. A defaulted destructor can be defined as deleted if a required subobject cannot be destroyed, for example because its destructor is inaccessible. A derived destructor is virtual even if you omit virtual; writing override checks that it overrides a virtual function.
When a Base* points to a Derived object created with new Derived, ordinary delete p; starts destruction with ~Derived(), and the Base destructor runs as part of that process. Without a virtual Base destructor, that deletion has undefined behavior unless a special deallocation function called a destroying operator delete is selected. A virtual destructor does not let you use delete[] through Base* to delete an array of Derived.
You can also declare virtual ~Base(); inside the class and define Base::~Base() = default; outside it without repeating virtual. A destructor defaulted on its first declaration is user-declared but not user-provided; one defaulted after its first declaration is classified as user-provided.
Examples
#include <cstdio>
struct Trace {
~Trace() { std::puts("Base member destroyed"); }
};
struct Base {
virtual ~Base() = default;
Trace member;
};
struct Derived : Base {
~Derived() override { std::puts("Derived destructor"); }
};
int main() {
Base* p = new Derived;
delete p;
}
Result
Derived destructor Base member destroyed
`delete p;` first prints `Derived destructor`. Then the defaulted `Base` destructor destroys `member`, whose destructor prints `Base member destroyed`.
Related lessons
- C++ · Lesson 37 · Intermediate · Version: 2