Thursday, October 6, 2016

Virtual Destructor :)

When We use Pointers In Inheritance then the destructor of derived class is not called.
To follow the normal rule we can use Virtual Destructor

Following is a simple program to Illustrate the Above Concept

#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"Base Constructor Called\n";
}
virtual ~A()
{
cout<<"Base Destructor Called\n";
}
};
class B:public A
{
public:
B()
{
cout<<"Derived Constructor Called\n";
}
virtual~B()
{
cout<<"Derived Destructor Called\n";
}
};
main()
{   A *p=new B();
delete(p);
}

Output:













And if we donot use virtual destructor then the above program gives the following output