< Previous | Contents | Next >
The Simple Boss program demonstrates inheritance. In it, I define a class for lowly enemies, Enemy. From this class, I derive a new class for tough bosses that the player has to face, Boss. Then, I instantiate an Enemy object and call its Attack() member function. Next, I instantiate a Boss object. I’m able to call Attack() for the Boss object because it inherits the member function from Enemy. Finally, I call the Boss object’s SpecialAttack() member function, which I defined in Boss, for a special attack. Since I define SpecialAttack() in Boss, only Boss objects have access to it. Enemy objects don’t have this special attack at their disposal. Figure 10.2 shows the results of the program.
Figure 10.2
The Boss class inherits the Attack() member function and then defines its own SpecialAttack()
member function.
334 Chapter 10 n Inheritance and Polymorphism: Blackjack
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 simple_boss.cpp.
//Simple Boss
//Demonstrates inheritance
#include <iostream> using namespace std;
class Enemy
{
public:
int m_Damage;
Enemy();
void Attack() const;
};
Enemy::Enemy(): m_Damage(10)
{}
void Enemy::Attack() const
{
cout << "Attack inflicts " << m_Damage << " damage points!\n";
}
class Boss : public Enemy
{
public:
int m_DamageMultiplier;
Boss();
void SpecialAttack() const;
};
Boss::Boss():
m_DamageMultiplier(3)
{}
void Boss::SpecialAttack() const
{
cout << "Special Attack inflicts " << (m_DamageMultiplier * m_Damage); cout << " damage points!\n";
}
int main()
{
cout << "Creating an enemy.\n"; Enemy enemy1;
cout << "\nCreating a boss.\n"; Boss boss1;
boss1.Attack(); boss1.SpecialAttack();
return 0;
}