< Previous | Contents | Next >

Introducing the Overriding Boss

Program

The Overriding Boss program demonstrates calling and overriding base class member functions in a derived class. The program creates an enemy that taunts the player and then attacks him. Next, the program creates a boss from a derived class. The boss also taunts the player and attacks him, but the interesting thing is that the inherited behaviors of taunting and attacking are changed for the boss (who is a bit cockier than the enemy). These changes are accomplished through function overriding and calling a base class member function. Figure 10.3 shows the results of the program.


image

Figure 10.3

The Boss class inherits and overrides the base class member functions Taunt() and Attack(), creating new behaviors for the functions in Boss.

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 overriding_boss.cpp.

//Overriding Boss

//Demonstrates calling and overriding base member functions #include <iostream>

using namespace std;

342 Chapter 10 n Inheritance and Polymorphism: Blackjack



class Enemy

{

public:

Enemy(int damage = 10); void virtual Taunt() const;

void virtual Attack() const;


//made virtual to be overridden

//made virtual to be overridden


private:

int m_Damage;

};


Enemy::Enemy(int damage): m_Damage(damage)

{}


void Enemy::Taunt() const

{

cout << "The enemy says he will fight you.\n";

}


void Enemy::Attack() const

{

cout << "Attack! Inflicts " << m_Damage << " damage points.";

}


class Boss : public Enemy

{

public:

Boss(int damage = 30);

void virtual Taunt() const; //optional use of keyword virtual void virtual Attack() const; //optional use of keyword virtual

};


Boss::Boss(int damage):

Enemy(damage) //call base class constructor with argument

{}


void Boss::Taunt() const //override base class member function

{

cout << "The boss says he will end your pitiful existence.\n";

}

Calling and Overriding Base Class Member Functions 343


void Boss::Attack() const //override base class member function

{

Enemy::Attack(); //call base class member function cout << " And laughs heartily at you.\n";

}


int main()

{

cout << "Enemy object:\n"; Enemy anEnemy; anEnemy.Taunt(); anEnemy.Attack();


cout << "\n\nBoss object:\n"; Boss aBoss;

aBoss.Taunt(); aBoss.Attack();


return 0;

}