Virtual Destructor

Deleting a derived class object using a pointer to a base class 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.

// CPP program without <a href="#">virtual destructor</a>
// causing undefined behavior
#include<iostream>
using namespace std;
class base {
  public:
    base()    
    { cout<<"Constructing base \n"; }
    ~base()
    { cout<<"Destructing base \n"; }    
};
class derived: public base {
  public:
    derived()    
    { cout<<"Constructing derived \n"; }
    ~derived()
    { cout<<"Destructing derived \n"; }
};
int main(void)
{
  derived *d = new derived(); 
  base *b = d;
  delete b;
  getchar();
  return 0;
}

Although the output of following program may be different on different compilers, when compiled using Dev-CPP, it prints following:

Constructing base
Constructing derived
Destructing base

Making base class destructor virtual guarantees that the object of derived class is destructed properly, i.e., both base class and derived class destructors are called. For example,

// A program with <a href="#">virtual destructor</a>
#include<iostream>
using namespace std;
class base {
  public:
    base()    
    { cout<<"Constructing base \n"; }
    virtual ~base()
    { cout<<"Destructing base \n"; }    
};
class derived: public base {
  public:
    derived()    
    { cout<<"Constructing derived \n"; }
    ~derived()
    { cout<<"Destructing derived \n"; }
};
int main(void)
{
  derived *d = new derived(); 
  base *b = d;
  delete b;
  getchar();
  return 0;
}

Output:

Constructing base
Constructing derived
Destructing derived
Destructing base

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

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

Skip to toolbar