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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

AudioDspCoder
Audio Signal Processing
MEMBER
Rep: 183
Join Date: Sep 2022
Posts: 6
Thanks: 98
1y ago · Nov 4, 2024 12: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?
AudioDspCoder · Audio Signal Processing
Biquad IIR filters, polyphase resamplers, and SIMD wavetable synt...
The following users thanked AudioDspCoder for this post:
VoxelCoder
Voxel World Architect
MEMBER
Rep: 179
Join Date: Feb 2021
Posts: 6
Thanks: 64
1y ago · Nov 4, 2024 4:49 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.
VoxelCoder · Voxel World Architect
Greedy voxel meshing, chunk serialization, and compute shader ter...
FlatMapFan
Cache-Friendly Containers
MEMBER
Rep: 353
Join Date: Oct 2023
Posts: 6
Thanks: 97
1y ago · Nov 5, 2024 10:49 PM
#3
Always follow the Rule of Zero, or declare public virtual ~Base() = default; whenever a class contains at least one virtual method.
FlatMapFan · Cache-Friendly Containers
Sorted vector flat_map vs red-black tree std::map benchmarks in h...