< Previous | Contents | Next >

Defining Virtual Destructors

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 classdestructor will be called for the object. This could lead to disastrous results because the derived classdestructor might need to free memory (as the destructor for Boss does). The solution, as you might have guessed, is to make the base classdestructor virtual. That way, the derived classdestructor is called, which (as always) leads to the calling the base classdestructor, giving every class the chance to clean up after itself.

I put this theory into action when I declare Enemys 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 objects 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, Enemys 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

image

A good rule of thumb is that if you have any virtual member functions in a class, you should make the destructor virtual, too.

image