Why do we need a pure virtual destructor in C++?

C++Server Side ProgrammingProgramming

There are no ill-effects of allowing a pure virtual destructor in C++ program. It is must to provide a function body for pure virtual destructor as derived class’s destructor is called first before the base class destructor, so if we do not provide a function body, it will find out nothing to be called during object destruction and error will occur. We can make easily an abstract class by making a pure virtual destructor with its definition.

Example Code

 Live Demo

#include <iostream>
using namespace std;

class B {
   public: virtual ~B()=0; // Pure virtual destructor
};

B::~B() {
   cout << "Pure virtual destructor is called";
}

class D : public B {
   public: ~D() {
   cout << "~Derived\n";
   }
};

int main() {
   B *b = new D();
   delete b;
   return 0;
}

Output

~Derived
Pure virtual destructor is called
raja
Published on 03-Apr-2019 15:59:56
Advertisements