Pure virtual destructor in C++ with code example

In this post, we will learn about pure virtual destructor in C++. We can have a pure virtual destructor in a C++ program, provided the destructor has a function body. The reason behind this is that destructors are called in reverse order of the class derivation i. e. the derived class destructor is called first and then the base class destructor. Therefore, if we do not provide any function body, an error occurs since there is nothing to be called during object destruction.

See the below example program to understand the pure virtual destructor.

#include <iostream>
using namespace std;

class BaseClass{
    public:
        virtual ~BaseClass() = 0;
};

class DerivedClass : public BaseClass{
    public:
        ~DerivedClass(){
            cout << "call to ~DerivedClass()" << endl;
        }
};

int main()
{
    BaseClass *bc = new DerivedClass();
    delete bc;
    return 0;
}

Output:

(.text$_ZN12DerivedClassD1Ev[_ZN12DerivedClassD1Ev]+0x4a): undefined reference to `BaseClass::~BaseClass()'

As can be seen, when we execute the above code, we get an error as there is no function body for the virtual destructor.

Now have a look at this program.

#include <iostream>
using namespace std;

class BaseClass{
    public:
        virtual ~BaseClass() = 0;
};

BaseClass::~BaseClass(){
    cout << "call to pure virtual destructor." << endl;
}

class DerivedClass : public BaseClass{
    public:
        ~DerivedClass(){
            cout << "call to ~DerivedClass()" << endl;
        }
};

int main()
{
    BaseClass *bc = new DerivedClass();
    delete bc;
    return 0;
}

Output:

call to ~DerivedClass()
call to pure virtual destructor.

As we can see now, we have provided a function body for the destructor and hence the program works fine.

Note that a class with a pure virtual destructor is an abstract class.

To learn about virtual destructor in C++, see this post: Virtual Destructor in C++

Leave a Reply

Your email address will not be published. Required fields are marked *