A base class destructor must be declared virtual, in order for the derived class destructor to be called when the object is deleted through a base class pointer.
"Having virtual functions indicate that a class is meant to act as an interface to derived classes, and when it is, an object of a derived class may be destroyed through a pointer to the base."
A virtual destructor example:
// deleting through a base class pointer
int main()
{
CDog* pDog = new CDomesticDog();
delete pDog;
return 0;
}
// base class CDog
class CDog {
public:
virtual ~CDog() { // virtual destructor (must be declared virtual in base class).
}
};
// derived class CDomesticDog
class CDomesticDog : public CDog {
char* m_pData;
public:
CDomesticDog() {
m_pData = new char[128] { };
}
~CDomesticDog() override { // derived class destructor will be called. resources will be freed. override is optional but recommended.
delete m_pData;
}
};