< Previous | Contents | Next >
When you use a pointer to a base class to point to an object of a derived class, you have a potential problem. When you delete the pointer, only the base class’ destructor will be called for the object. This could lead to disastrous results because the derived class’ destructor might need to free memory (as the destructor for Boss does). The solution, as you might have guessed, is to make the base class’ destructor virtual. That way, the derived class’ destructor is called, which (as always) leads to the calling the base class’ destructor, giving every class the chance to clean up after itself.
I put this theory into action when I declare Enemy’s destructor virtual.
virtual ~Enemy();
352 Chapter 10 n Inheritance and Polymorphism: Blackjack
In main(), when I delete the pointer pointing to the Boss object with the following line, the Boss object’s destructor is called, which frees the memory on the heap that m_pDamageMultiplier points to and displays the message In Boss
destructor, deleting m_pMultiplier.
delete pBadGuy;
Then, Enemy’s destructor is called, which frees the memory on the heap that m_pDamage points to and displays the message In Enemy destructor, deleting m_pDamage. The object is destroyed, and all memory associated with the object is freed.
Tric k
A good rule of thumb is that if you have any virtual member functions in a class, you should make the destructor virtual, too.