Tuesday, May 7, 2019

C++: to declare the destructor of the base class as virtual


If the destructor of the base class is not declared as virtual, the derived class may not be correctly destroyed in some scenarios. Use the following code as an example:

#include<iostream>
 
using namespace std;
 
class base {
  public:
    base()     
    { cout << "in base()" << endl; }
   
    ~base()
    { cout << "in ~base()" << endl; }     
};
 
class derived : public base {
  public:
    derived()     
    { cout << "in derived()" << endl; }
   
    ~derived()
    { cout << "in ~derived()" << endl; }
};
 
int main(void)
{
  base *b = new derived();  
  delete b;
  return 0;
}


The output of the program:
in base()
in derived()
in ~base()


The destructor of the derived class is not called.

When we change the destructors to virtual:

#include<iostream>
 
using namespace std;
 
class base {
  public:
    base()     
    { cout << "in base()" << endl; }
   
    virtual ~base()
    { cout << "in ~base()" << endl; }     
};
 
class derived : public base {
  public:
    derived()     
    { cout << "in derived()" << endl; }
   
    virtual ~derived()
    { cout << "in ~derived()" << endl; }
};
 
int main(void)
{
  base *b = new derived();  
  delete b;
  return 0;
}



The output of the program is changed to:
in base()
in derived()
in ~derived()
in ~base()




No comments:

 
Get This <