G2Labs Grzegorz Grzęda
Virtual destructor in C++
May 6, 2023
You may have noticed, that every time, when an interface is being introduced, there is a virtual destructor declared.
But actually, what for is that destructor need to be virtual
?
Begin with the end in memory
When we construct our objects everything is fine. But what if:
|
|
We would get:
Where is the Deriv Dtor
? What if we were supposed to do something important in the destructor? Some cleanup, send a log entry? This is undefined behavior.
But, if we add that virtual
to the Base::~Base()
we will get the result as expexted:
Now everything is fine.
So when should we make dtors virtual? Well, when compiling with -Wall
flag, the compiler will suggest the answer: if at leas one method is virtual (even not purely), we should make the dtor virtual as well.