In this C++ tutorial, you will learn about Virtual Destructor, how to define a virtual destructor, and its importance during some special cases, with examples.

C++ Virtual Destructor

C++ Virtual Destructor is used for a base class, when there are derived class or child class objects of the base class type, and these derived class objects have to be destroyed.

Examples

ADVERTISEMENT

1. Class without Virtual Destructor

Consider a scenario where there are two classes: A and C, of which A is base class and C is a derived class from A.

We create an object of type C, and assign it to the pointer of its base class A. In this scenario, when we delete the derived class object, the destructor for derived class object is not executed, but only the base class object destructor.

Above said behaviour can be realised using the following program.

C++ Program

#include <iostream>
using namespace std;

class A {
public:
    ~A() {
        cout << "Base class object destroyed." << endl;
    }
};

class C: public A {
public:
    ~C() {
        cout << "Derived class object destroyed." << endl;
    }
};

int main() {
    C *c = new C();
    A *a = c;
    delete a;
}

Output

Base class object destroyed.
Program ended with exit code: 0

The base class object destructor has been called, but the derived class object destructor is not called.

We require the derived class object destructor be called as well.

To fix this issue, declare the base class object destructor as virtual.

2. Class with Virtual Destructor

In the following program, we declare the destructor of base class A, as virtual.

C++ Program

#include <iostream>
using namespace std;

class A {
public:
    virtual ~A() {
        cout << "Base class object destroyed." << endl;
    }
};

class C: public A {
public:
    ~C() {
        cout << "Derived class object destroyed." << endl;
    }
};

int main() {
    C *c = new C();
    A *a = c;
    delete a;
}

Output

Derived class object destroyed.
Base class object destroyed.
Program ended with exit code: 0

Now, both the derived class object destructor and base class object destructor are called.

Conclusion

In this C++ Tutorial, we learned what a Virtual Destructor is, how it is used in the scenario of base and derived class objects, with the help of examples.