In C++, a virtual destructor is a destructor declared with the virtual keyword in the base class. It is used in polymorphic class hierarchies to ensure that the correct destructor is called when deleting an object through a pointer to the base class.
When a derived class inherits from a base class, and a pointer to the derived class is assigned to a pointer of the base class, deleting the base class pointer can lead to undefined behavior if the destructor is not virtual. In such cases, the base class’s destructor may be called, but the derived class’s destructor won’t be invoked, which can cause resource leaks or incorrect cleanup.
By declaring the base class destructor as virtual, you enable dynamic binding of the destructor call. It means that when you delete an object through a pointer to the base class, the destructor of the most derived class in the inheritance hierarchy will be called first, followed by the destructors of the base classes in the reverse order of their construction.
Here’s an example to illustrate the usage of a virtual destructor:
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Base</span> {
<span class="hljs-keyword">public</span>:
    <span class="hljs-keyword">virtual</span> ~<span class="hljs-built_in">Base</span>() {
        <span class="hljs-comment">// Base class destructor</span>
    }
};
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Derived</span> : <span class="hljs-keyword">public</span> Base {
<span class="hljs-keyword">public</span>:
    ~<span class="hljs-built_in">Derived</span>() {
        <span class="hljs-comment">// Derived class destructor</span>
    }
};
<span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    Base* ptr = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Derived</span>();
    <span class="hljs-keyword">delete</span> ptr;  <span class="hljs-comment">// Calls the destructor of Derived first, then Base</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
In this example, deleting the ptr pointer, which is of type Base*, correctly invokes the destructor of the Derived class because the Base class destructor is declared as virtual. Without the virtual keyword, only the Base class destructor would be called, potentially causing resource leaks or incomplete cleanup in the Derived class.
