C++ virtual destructor

Poby’s Home
Feb 23, 2021

--

virtualneeded if you are writing a class with inheritance in mind.

The problem of a class without a virtual destructor

A program with a BUG!!

As you can see, memory is allocated but never deallocated!!

The reason is, when derived get deleted, it does not know if the destructor of Derived should be called or not!

Solution

To hint that its derived class’ destructor needs to be called, you need to add virtual in front of Base class’ destructor.

result

Summary

If you design a class that will be inherited, you should have a virtual destructor.

--

--

No responses yet