Home / Forums / Why should virtual destructors always be declared in polymorphic base classes? [Part 4]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

Why should virtual destructors always be declared in polymorphic base classes? [Part 4]

BitTwiddler
Bitwise Algorithms
VIP
Rep: 79
Join Date: Jan 2020
Posts: 6
Thanks: 71
4y ago · Mar 25, 2022 6:14 PM
#1
What happens if I delete an instance of a derived class through a pointer to its base class when the base class destructor is not marked virtual?
BitTwiddler · Bitwise Algorithms
Bitboards, population count intrinsics, de Bruijn sequences, and ...
The following users thanked BitTwiddler for this post:
VtableExplorer
ABI & Object Layouts
MEMBER
Rep: 119
Join Date: Jun 2025
Posts: 6
Thanks: 99
4y ago · Mar 25, 2022 8:57 PM
#2
If the base destructor is not virtual, calling delete on a Base* pointing to a Derived instance invokes Undefined Behavior (UB)! In practice, the compiler will only execute the Base destructor, leaving any dynamically allocated members in the Derived class leaked in memory.
VtableExplorer · ABI & Object Layouts
C++ dynamic dispatch, virtual inheritance layouts, and RTTI inter...
CustomVector
STL Container Author
MEMBER
Rep: 183
Join Date: Feb 2021
Posts: 6
Thanks: 47
4y ago · Mar 26, 2022 1:57 AM
#3
Always follow the Rule of Zero, or declare public virtual ~Base() = default; whenever a class contains at least one virtual method.
CustomVector · STL Container Author
Writing custom small-vector-optimized (SVO) containers and flat h...