Virtual Destructor

Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, following program results in undefined behavior. 

A class may have virtual destructor but it cannot have a virtual constructor. It is necessary to have virtual destructor, otherwise we might face consequences.  Check this link here.

#include <iostream>
using namespace std;

class Army                         // Class declaration
{
public:
    ~Army() { cout << "Deleting Army" << endl; }
};

class ArmyHospital : public Army 
{
public:
    ~ArmyHospital() { cout << "Deleting ArmyHospital" << endl; }
};


int main() 
{

    ArmyHospital* hos = new ArmyHospital;
    delete hos;
    cout << "delete hos is finished" << endl << endl;

    Army* major = new ArmyHospital;
    delete major;
    cout << "delete major is finished" << endl << endl;

    return 0;
}

Output:
1
2
3
4
5
6
7
Deleting ArmyHospital
Deleting Army
delete hos is finished

Deleting Army
delete major is finished

delete hos; cleans up both Army and ArmyHospital. On the other hand, delete major doesn't delete the ArmyHospital. ArmyHospital's memory left hanging. Now, let's add the virtual modifier to see what happens. 

#include <iostream>
using namespace std;

class Army                         // Class declaration
{
public:
    virtual
    ~Army() { cout << "Deleting Army" << endl; }
};

class ArmyHospital : public Army 
{
public:
    ~ArmyHospital() { cout << "Deleting ArmyHospital" << endl; }
};


int main() 
{

    ArmyHospital* hos = new ArmyHospital;
    delete hos;
    cout << "delete hos is finished" << endl << endl;

    Army* major = new ArmyHospital;
    delete major;
    cout << "delete major is finished" << endl << endl;

    return 0;
}

Output:
1
2
3
4
5
6
7
8

Deleting ArmyHospital
Deleting Army
delete hos is finished

Deleting ArmyHospital
Deleting Army
delete major is finished


Having the modifier virtual, takes care of deleting the memory smoothly.

For an abstract class (Army), a virtual-table pointer in the object is needed, so making the destructor virtual doesn't (as far as I'm aware) have a high cost in terms of space or runtime performance.

Reference








Comments