Consider a situation where a derived class object is created using new. The address of this object can be assigned to a pointer to a base class object. Now if we delete the pointer, since the pointer is a base class pointer this would result in a call to the base class destructor. Ideally, firstly the derived class destructor should be called followed by the base class destructor. This can be ensured by using a virtual destructor in the base class. The following program shows how this can be implemented.
#include <iostream.h>
class base
{
public :
base( )
{
cout << endl << “In base class constructor” ;
}
virtual ~base( )
{
cout << endl << “In base class destructor” ;
}
} ;
class derived : public base
{
public :
derived( )
{
cout << endl << “In derived class constructor” ;
}
~derived( )
{
cout << endl << “In derived class destructor” ;
}
} ;
void main( )
{
base *b ;
b = new derived ;
delete b ;
}