Virtual Destructor

We already studies what is Destructor and virtual function. The combination of Virtual keyword what we studied in Virtual function and Destructor is nothing but Virtual Destructor. A virtual destructor is used to free up the memory space allocated by the derived class object or instance while deleting instances of the derived class using a base class pointer object. A base or parent class destructor use the virtual keyword that ensures both base class and the derived class destructor will be called at run time, but it called the derived class first and then base class to release the space occupied by both destructors.

CODE

EG 1 . Creating a parent class with virtual destructor.

#include <iostream>
using namespace std;

class BaseClass {
  public:
    BaseClass() {
        cout << "Base class constructor invoked" << endl;
    }
    virtual ~BaseClass() {
        cout << "Base class virtual destructor invoked" << endl;
    }
};

class DerivedClass : public BaseClass {
  public:
    DerivedClass() {
        cout << "Derived class constructor invoked" << endl;
    }
    ~DerivedClass() {
        cout << "Derived class destructor invoked" << endl;
    }
};

int main() {
    //UPCASTING
    BaseClass* obj1 = new DerivedClass();
    //We can delete object inside code itself
    delete obj1;
}