< Previous | Contents | Next >

Deriving from a Base

Class

I derive the Boss class from Enemy when I define Boss with the following line:

class Boss : public Enemy

Boss is based on Enemy. In fact, Enemy is called the base class (or superclass) and Boss the derived class (or subclass). This means that Boss inherits Enemys data members and member functions, subject to access controls. In this case, Boss inherits and can directly access m_Damage and Attack(). Its as if I defined both m_Damage and Attack() in Boss.


Hin t

image

You might have noticed that I made all of the members of the classes pubic, including their data members. I did this because it makes for the simplest first example of a base and derived class. You also might have noticed that I used the keyword public when deriving Boss from Enemy. For now, don’t worry about this. I’ll cover it all in the next example program, Simple Boss 2.0.

image

336 Chapter 10 n Inheritance and Polymorphism: Blackjack


To derive classes of your own, follow my example. After the class name in a class definition, put a colon followed by an access modifier (such as public), followed by the name of the base class. Its perfectly acceptable to derive a new class from a derived class, and sometimes it makes perfect sense to do so. However, to keep things simple, Im only going to deal with one level of inheritance in this example.

There are actually a few base class member functions that are not inherited by derived classes. They are as follows:

n Constructors

n Copy constructors

n Destructors

n Overloaded assignment operators

You have to write your own versions of these in the derived class.