Thursday 11 January 2007

Need for "Virtual Destructor"

If we have 2 classes, say

class CBase{
public:
CBase(){}
~CBase(){}
};

class CDerived : public CBase{
public:
CDerived(){}
~CDerived(){}
};

and if we do,

CBase* pBase = new CDerived;
delete pBase;

Since CBase does not have a virtual destructor, the delete pBase invokes the destructor of the class of the pointer (CBase::~CBase()), rather than the destructor of the most derived type (CDerived::~CDerived()). And as you can see, this is the wrong thing to do in the above scenario.

A class must have a virtual destructor if it meets both of the following criteria:

  • You do a delete pBase.
  • pBase actually points to a derived class object.

1 comments:

Prashanth Gedde N said...

Its wrong if we think that we need to have "Virtual Destructors" only if we have atleast one virtual function in base class.

As said earlied if the following 2 conditions are true, we need to have a virtual destructor in Base

1. If we delete the base pointer pBase
2. And pBase is pointing to derived class instance.