virtual destructor

virtual destructor

#include<iostream>
using namespace std;

class Base1
{
  public:
  Base1()
  {
      cout<<"Base1"<<endl;
  }
  virtual ~Base1()
  {
      cout<<"Destruct Base1"<<endl;
  }
};

class Derived1:public Base1
{
  public:
  Derived1()
  {
      cout<<"Derived 1"<<endl;
  }
  ~Derived1()
  {
      cout<<"Destruct Derived 1"<<endl;
  }
};

class Base2
{
  public:
  Base2()
  {
      cout<<"Base 2"<<endl;
  }

  ~Base2()
  {
      cout<<"Destruct Base  2"<<endl;
  }
};

class Derived2:public Base2
{
  public:
  Derived2()
  {
      cout<<"Derived 2"<<endl;
  }
  ~Derived2()
  {
      cout<<"Destruct Derived 2"<<endl; // You cant see it because
~Base2() is not virtual
  }
};

int main()
{
    {
        Base1 *p=new Derived1();
        Base2 *k=new Derived2();
        delete p;
        delete k;
    }

    return 0;
}

OUTPUT

Base 1

Derived 1

Base 2

Derived 2

Destruct Base 1

Destruct Derived 1

Destruct Base 2

// Destruct Derived 2 is not written here, because of non-virtual Base destructor