Programming Language

C++ Virtual Destructor And When It Is Needed

Within a Base class, there can be destructors which are virtual. For proper destruction of the open when the particular program exits, virtual destructors within the Base class are essential, especially when Upcasting is done. In an event that a declared object having a type base class and the destructor within the base class is not virtual, then the instance of the child class will not call the derived class destructor, but rather call the bass class destructor. Therefore, virtualizing the destructor within the base class will help make sure that the derived class destructor is called right before the base class destructor is called.

So when do we really need a virtual destructor?

We need virtual destructors when we are able to delete an instance of a derived class via a pointer to base class:

 

class Base

{

// some virtual methods

};

 

class Derived : public Base

{

~Derived()

{

// Do some important cleanup

}

}

Here, you will observe that the Base’s destructor wasn’t declared to be virtual. Okay let us take a look at the snippet below:

 

Base *b = new Derived();

// use b

delete b; // Here’s the problem!

 

Since the Base destructor is not virtual and b is a Base* indicating a Derived object, delete b has vague behavior. In a lot of usage, the call to the destructor will be determined like any non-virtual code, implying that the destructor of the base class will be called however not the one of the derived class, bringing about leak in resources.

To summarize everything, dependably make base classes’ destructors virtual when they are intended to be controlled polymorphically.

In the event that you need to keep the cancellation of an occasion through a base class pointer, you can make the base class destructor secured and nonvirtual; thusly, the compiler won’t give you a chance to call delete on a base class pointer.

Leave a Reply