What is Virtual Destructor In C++

Diganta Chaudhuri
2 min readMay 5, 2021

If you want to learn what is distractor click this

Deleting a derived class object using a pointer of base class type that has non-virtual destructor results in undefined behavior.

To correct this situation, the base class should be defined with a virtual destructor.

So without a virtual distractor See what happen when we create a pointer object in the main() function Here the code:

A simple program for distractor:-

Without Virtual Distractor

The output of this code is:

Now let's write some code like this:

Here you see after deleting obj_PTRderived if we create Create Base *objPTR_base2 = new Derived(); and after that, if we delete this like this delete objPTR_base2;

Now, the output of the code is:

Here you can see no output for “Distractor of Derived called”. This is problematic so How To fix this Answer is obviously — virtual destructor

So fixed code is

The output of this code is:

That is it Thank you for reading.

If you connect with me

Linkedin — https://www.linkedin.com/in/diganta-chaudhuri-8451251b6

Twitter — https://twitter.com/Digantachaudhu2

Thank you❤

--

--