< Previous | Contents | Next >

Calling Base Class Member

Functions

You can directly call a base class member function from any function in a derived class. All you have to do is prefix the class name to the member function name with the scope resolution operator. Thats what I do when I define the overridden version of Attack() for the Boss class.

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

{

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

}

The code Enemy::Attack(); explicitly calls the Attack() member function of

Enemy. Because the Attack() definition in Boss overrides the classinherited

346 Chapter 10 n Inheritance and Polymorphism: Blackjack


version, its as if Ive extended the definition of what it means for a boss to attack. What Im essentially saying is that when a boss attacks, the boss does exactly what an enemy does and then laughs. When I call the member function for a Boss object in main() with the following line, BossAttack() member function is called because Ive overloaded Attack().

aBoss.Attack();

The first thing that BossAttack() member function does is explicitly call Enemys Attack() member function, which displays the message Attack! Inflicts 30 damage points. Then, BossAttack() member function displays the message And laughs heartily at you.


Tric k

image

You can extend the way a member function of a base class works in a derived class by overriding the base class method and then explicitly calling the base class member function from this new definition in the derived class and adding some functionality.

image