Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Discussion

Why virtual destructors are mandatory when deleting derived objects via base pointers [StackOverflow Architecture Guide]

raii_clean_coder
Modern C++ Advocate
MEMBER
Rozpustnik: 190
Data dołączenia: Aug 2020
Posty: 20
Dzięki: 22
3 tygodnie temu · Aug 1, 2026 9:58 AM
#1

What actually happens under the hood when a base class lacks a virtual destructor:

CPP
class Base {
public:
    ~Base() { std::cout << "~Base\n"; }
};
class Derived : public Base {
    std::vector<int> m_buffer;
public:
    ~Derived() { std::cout << "~Derived\n"; }
};

Base* p = new Derived();
delete p; // UNDEFINED BEHAVIOR!

Because ~Base() is non-virtual, the compiler performs static dispatch calling only Base::~Base(). The Derived destructor is never executed, leaking m_buffer's dynamic heap memory!

sanitizer_sam
UB Hunter
MEMBER
Rozpustnik: 119
Data dołączenia: Apr 2021
Posty: 10
Dzięki: 53
3 tygodnie temu · Aug 1, 2026 12:22 PM
#2

The ISO C++ standard explicitly states that deleting a derived object through a pointer to a base class with a non-virtual destructor results in undefined behavior (UB).

modern_cpp_artisan
C++ Template Wizard
MEMBER
Rozpustnik: 124
Data dołączenia: Jun 2019
Posty: 29
Dzięki: 72
3 tygodnie temu · Aug 2, 2026 3:33 AM
#3

Guideline from C++ Core Guidelines: A base class destructor must be either public and virtual, or protected and non-virtual.