Virtual Destructor in C++

In this C++ tutorial, we are going to discuss the destructor, virtual destructor, its implementation and when to use virtual destructor.

Why Virtual Destructor

When we need to delete a derived class object using a pointer to a base class, then the base class should be defined with a virtual destructor.

Syntax :-                      ~virtual base();

Code Snippet to delete derived class object using pointer to base class

derived *d = new derived();   // creating a derived class object pointer

base *b = d;                 // creating a base class pointer holding address of derived class object

delete b;                     // deleting object of derived class

Making base class destructor virtual guarantees that both base class and derived class destructor are called.

C++ Code implementation of Virtual Destructor

#include<bits/stdc++.h> 

using namespace std; 

  class base
 { 
    public: 
  
      virtual ~base() 
   {
       cout<<"Base class Destructor called"<<endl;
   }	 
}; 

  class derived: public base 
{ 
   public: 

    	~derived() 
   {
       cout<<"Derived class destructor called"<<endl;
   } 
}; 

   int main() 
 { 
   derived *d = new derived(); 
   
    base *b = d; 
   
    delete b; 
} 

OUTPUT

Derived class destructor called

Base class Destructor called

Pure Virtual Destructor in C++

When a destructor is initialized with value 0. It is called virtual destructor, it is declared in base class. Like virtual destructor, pure virtual destructor is also possible. But it should be defined in base class.



Syntax:-         virtual ~base()=0;

CPP Code implementation of pure virtual destructor

Now, here is the c++ code to implement it.

 #include <bits/stdc++.h> 
 using namespace std;
  
   class Base 
 { 
   public: 

  virtual ~Base()=0; // Pure virtual destructor 

 }; 

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

   class Derived : public Base 
 { 
     public: 
  
    ~Derived() 
  { 
    cout << "Derived class destructor is called"<<endl; 
  } 
}; 

  int main() 
{ 
  Base *b = new Derived(); 
  delete b; 
}

OUTPUT

Derived class destructor is called
Pure virtual destructor is called

Thanks For Reading !!

Please, ask your doubts and for any suggestion comment in the comment section below.

Also read,

Leave a Reply

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