< Previous | Contents | Next >

Calling Base Class Constructors

As youve seen, the constructor for a base class is automatically called when an object of a derived class is instantiated, but you can also explicitly call a base class constructor from a derived class constructor. The syntax for this is a lot like the syntax for a member initialization list. To call a base class constructor from a derived class constructor, after the derived constructors parameter list, type a colon followed by the name of the base class, followed by a set of parentheses containing whatever parameters the base class constructor youre calling needs. I do this in the Boss constructor, which says to explicitly call the Enemy constructor and pass it damage.

Boss::Boss(int damage):

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

{}

This allows me to pass the Enemy constructor the value that gets assigned to

m_Damage, rather than just accepting its default value.

When I first instantiate aBoss in main(), the Enemy constructor is called and passed the value 30, which gets assigned to m_Damage. Then, the Boss constructor runs (which doesnt do much of anything) and the object is completed.

344 Chapter 10 n Inheritance and Polymorphism: Blackjack


Hi n t

image

Being able to call a base class constructor is useful when you want to pass specific values to it.

image