Next, to ensure access to those display_capacity
functions, you need
to install a virtual version of display_capacity
in the
railroad_car
class:
class railroad_car { public: railroad_car ( ) { } virtual void display_short_name ( ) { } virtual void display_capacity ( ) { } };
Although this version of the display_capacity
does no displaying,
you accomplish two objectives by defining it. First, because this version
is marked virtual, C++ knows that railroad_car
pointers may be
directed at run time to class objects that require versions of
display_capacity
found in railroad_car
subclasses.
Second, assuming that there are no definitions for display_capacity
in the engine
and caboose
classes, inheritance ensures that
the version found in the railroad_car
class is the version used when
engines or cabooses are encountered. Thus, the do-nothing version of
display_capacity
found in the railroad_car
class acts as a
safety net for class objects that otherwise would not have a
display_capacity
member function.
*----------------* | railroad_car | *----------------* ^ ^ ^ ^ *----------------------------------------* | | | | *----------------------* | | | | *--------------* | | | | | *----------* *----------* *----------* *----------* | box_car | | tank_car | | engine | | caboose | *----------* *----------* *----------* *----------* --------------------------------- --------------------------------- These classes define their own These classes inherit the version versions of the display_capacity of the display_capacity function function defined in railroad_car