< Previous | Contents | Next >
Introducing the Polymorphic Bad Guy
The Polymorphic Bad Guy program demonstrates how to achieve polymorphic behavior. It shows what happens when you use a pointer to a base class to call inherited virtual member functions. It also shows how using virtual destructors ensures that the correct destructors are called for objects pointed to by pointers to a base class. Figure 10.4 shows the results of the program.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 10 folder; the filename is polymorphic_bad_guy.cpp.
348 Chapter 10 n Inheritance and Polymorphism: Blackjack
Figure 10.4
Through polymorphism the correct member functions and destructors are called for objects pointed to by pointers to a base class.
//Polymorphic Bad Guy
//Demonstrates calling member functions dynamically #include <iostream>
using namespace std;
class Enemy
{
public:
Enemy(int damage = 10); virtual ~Enemy();
void virtual Attack() const;
protected:
int* m_pDamage;
};
Enemy::Enemy(int damage)
{
m_pDamage = new int(damage);
}
Introducing Polymorphism 349
Enemy::~Enemy()
{
cout << "In Enemy destructor, deleting m_pDamage.\n"; delete m_pDamage;
m_pDamage = 0;
}
void Enemy::Attack() const
{
cout << "An enemy attacks and inflicts " << *m_pDamage << " damage points.";
}
class Boss : public Enemy
{
public:
Boss(int multiplier = 3); virtual ~Boss();
void virtual Attack() const;
protected:
int* m_pMultiplier;
};
Boss::Boss(int multiplier)
{
m_pMultiplier = new int(multiplier);
}
Boss::~Boss()
{
cout << "In Boss destructor, deleting m_pMultiplier.\n"; delete m_pMultiplier;
m_pMultiplier = 0;
}
void Boss::Attack() const
{
cout << "A boss attacks and inflicts " << (*m_pDamage) * (*m_pMultiplier)
<< " damage points.";
}
350 Chapter 10 n Inheritance and Polymorphism: Blackjack
int main()
{
cout << "Calling Attack() on Boss object through pointer to Enemy:\n"; Enemy* pBadGuy = new Boss();
pBadGuy->Attack();
cout << "\n\nDeleting pointer to Enemy:\n"; delete pBadGuy;
pBadGuy = 0;
return 0;
}