Sams Teach Yourself C++ in 21 Days

(singke) #1
Implementing Inheritance 395

12


This stripped-down program, which provides only the barest functionality to each
class, illustrates virtual functions in their purest form. Four classes are declared:
Dog,Cat,Horse, and Pig. All four are derived from Mammal.
On line 10,Mammal’s Speak()function is declared to be virtual. On lines 19, 25, 32, and
38, the four derived classes override the implementation of Speak().
On lines 46–64, the program loops five times. Each time, the user is prompted to pick
which object to create, and a new pointer to that object type is added to the array from
within the switchstatement on lines 50–62.
At the time this program is compiled, it is impossible to know which object types will be
created, and thus which Speak()methods will be invoked. The pointer ptris bound to
its object at runtime. This is called dynamic binding, or runtime binding, as opposed to
static binding, or compile-time binding.
On lines 65 and 66, the program loops through the array again. This time, each object in
the array has its Speak()method called. Because Speak()was virtual in the base class,
the appropriate Speak()methods are called for each type. You can see in the output that
if you choose each different type, that the corresponding method is indeed called.

ANALYSIS

FAQ
If I mark a member method as virtual in the base class, do I need to also mark it as vir-
tual in derived classes?
Answer:No, once a method is virtual, if you override it in derived classes, it remains vir-
tual. It is a good idea (though not required) to continue to mark it virtual—this makes
the code easier to understand.

How Virtual Functions Work ..........................................................................


When a derived object, such as a Dogobject, is created, first the constructor for the base
class is called, and then the constructor for the derived class is called. Figure 12.2 shows
what the Dogobject looks like after it is created. Note that the Mammalpart of the object
is contiguous in memory with the Dogpart.

FIGURE12.2
The Dogobject after it
is created.


Mammal

Dog

Dog Object

Mammal Part
Free download pdf