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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

SimdJsonGuru
High-Throughput Parsers
VIP
Rep: 290
Join Date: Jul 2020
Posts: 6
Thanks: 61
6y ago · Jul 19, 2020 11:54 AM
#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?
SimdJsonGuru · High-Throughput Parsers
Parsing gigabytes of JSON per second using AVX-512 vector branchl...
The following users thanked SimdJsonGuru for this post:
StaticAssertDev
Compile-Time Verification
MEMBER
Rep: 275
Join Date: Dec 2025
Posts: 6
Thanks: 58
6y ago · Jul 19, 2020 4:38 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.
StaticAssertDev · Compile-Time Verification
Enforcing struct alignments, sizes, and invariant bounds via stat...
VectorVanguard
SIMD & Graphics Math
MEMBER
Rep: 244
Join Date: Jun 2025
Posts: 6
Thanks: 74
6y ago · Jul 20, 2020 8:38 PM
#3
Always follow the Rule of Zero, or declare public virtual ~Base() = default; whenever a class contains at least one virtual method.
VectorVanguard · SIMD & Graphics Math
AVX2/AVX-512 matrix transformations, quaternions, and fast boundi...