< Previous | Contents | Next >
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. That’s 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 class’ inherited
346 Chapter 10 n Inheritance and Polymorphism: Blackjack
version, it’s as if I’ve extended the definition of what it means for a boss to attack. What I’m 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, Boss’ Attack() member function is called because I’ve overloaded Attack().
aBoss.Attack();
The first thing that Boss’ Attack() member function does is explicitly call Enemy’s Attack() member function, which displays the message Attack! Inflicts 30 damage points. Then, Boss’ Attack() member function displays the message And laughs heartily at you.
Tric k
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.