|
|
|
|
|
|
|
Mammal is derived from Animal and is declared on lines 2936. It adds no data. It overrides Reproduce(), however, providing a common form of reproduction for all Mammals. Fish must override Reproduce(), because Fish derives directly from Animal and cannot take advantage of Mammalian reproduction (and a good thing, too!). |
|
|
|
|
|
|
|
|
Mammal classes no longer have to override the Reproduce() function, but they are free to do so if they choose (as Dog does on line 76). Fish, Horse, and Dog all override the remaining pure virtual functions so that objects of their type can be instantiated. |
|
|
|
|
|
|
|
|
In the body of the program, an Animal pointer is used to point to the various derived objects in turn. The virtual methods are invoked; and, based on the runtime binding of the pointer, the correct method is called in the derived class. |
|
|
|
|
|
|
|
|
It would cause a compile-time error to try to instantiate an Animal or a Mammal, as both are abstract data types. |
|
|
|
|
|
|
|
|
Which Types Are Abstract? |
|
|
|
|
|
|
|
|
In one program, the class Animal is 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 may want Animal to be an abstract data type but Dog to be a class from which you can instantiate objects. |
|
|
|
|
|
|
|
|
On the other hand, if you are making an animated kennel, you may want to keep Dog as an abstract data type, 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. |
|
|
|
|
| DO | DON'T | | DO use abstract data types to provide common functionality for a number of related classes. | DON'T try to instantiate an object of an abstract data type. | | DO override all pure virtual functions. | | | DO make pure virtual any function that must be overridden. | |
|
|
|