486 Day 14
advantage of Mammalian reproduction (and a good thing, too!). Fishdoes this in lines
47–48.
Mammalclasses no longer have to override the Reproduce()function, but they are free to
do so if they choose, as Dogdoes on line 83. Fish,Horse, and Dogall override the
remaining pure virtual functions, so that objects of their type can be instantiated.
In the body of the main program, an Animalpointer is used to point to the various
derived objects in turn. The virtual methods are invoked, and based on the runtime bind-
ing of the pointer, the correct method is called in the derived class.
It would be a compile-time error to try to instantiate an Animalor a Mammal, as both are
abstract classes.
Which Classes Are Abstract? ........................................................................
In one program, the class Animalis abstract; in another, it is not. What determines
whether to make a class abstract?
The answer to this question is decided not by any real-world intrinsic factor, but by what
makes sense in your program. If you are writing a program that depicts a farm or a zoo,
you might want Animalto be an abstract class, but Dogto be a class from which you can
instantiate objects.
On the other hand, if you are making an animated kennel, you might want to keep Dogas
an abstract class and only instantiate types of dogs: retrievers, terriers, and so forth. The
level of abstraction is a function of how finely you need to distinguish your types.
DOuse abstract classes to provide com-
mon description of capabilities provided
in a number of related classes.
DOmake pure virtual any function that
must be overridden.
DON’Ttry to instantiate an object of an
abstract classes.
DO DON’T
Summary ..............................................................................................................
Today, you learned how to overcome some of the limitations in single inheritance. You
learned about the danger of percolating functions up the inheritance hierarchy and the
risks in casting down the inheritance hierarchy. You also learned how to use multiple
inheritance, what problems multiple inheritance can create, and how to solve them using
virtual inheritance.