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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

DynamicLinking
PE / ELF Linker Expert
MEMBER
Rep: 79
Join Date: Nov 2024
Posts: 6
Thanks: 102
1y ago · Nov 13, 2024 5:34 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?
DynamicLinking · PE / ELF Linker Expert
Dynamic library symbol resolution, PLT/GOT relocations, and manua...
The following users thanked DynamicLinking for this post:
IntrinsicsNinja
AVX2 & NEON Intrinsics
MEMBER
Rep: 261
Join Date: Apr 2023
Posts: 6
Thanks: 56
1y ago · Nov 13, 2024 6:58 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.
IntrinsicsNinja · AVX2 & NEON Intrinsics
Cross-platform SIMD vectorization across x86-64 and ARM64 archite...
MoveSemanticsX
Value Categories Expert
MEMBER
Rep: 223
Join Date: Dec 2025
Posts: 6
Thanks: 27
1y ago · Nov 14, 2024 11:58 PM
#3
Always follow the Rule of Zero, or declare public virtual ~Base() = default; whenever a class contains at least one virtual method.
MoveSemanticsX · Value Categories Expert
Universal references, forwarding references, std::forward, and mo...