Polymorphism 485
14
101: switch (choice)
102: {
103: case 1: pAnimal = new Dog(5,Brown);
104: break;
105: case 2: pAnimal = new Horse(4,Black);
106: break;
107: case 3: pAnimal = new Fish (5);
108: break;
109: default: fQuit = true;
110: break;
111: }
112: if (fQuit == false)
113: {
114: pAnimal->Speak();
115: pAnimal->Eat();
116: pAnimal->Reproduce();
117: pAnimal->Move();
118: pAnimal->Sleep();
119: delete pAnimal;
120: cout << endl;
121: }
122: }
123: return 0;
124: }
(1)Dog (2)Horse (3)Bird (0)Quit: 1
Animal constructor...
Mammal constructor...
Dog constructor...
Whoof!...
Dog eating...
Dog reproducing....
Dog running...
Dog snoring...
Dog destructor...
Mammal destructor...
Animal destructor...
(1)Dog (2)Horse (3)Bird (0)Quit: 0
On lines 7–21, the abstract class Animalis declared. Animalhas nonpure virtual
accessors for itsAge, which are shared by all Animalobjects. It has five pure vir-
tual functions,Sleep(),Eat(),Reproduce(),Move(), and Speak().
Mammalis derived from Animalon lines 29–37, and adds no data. It overrides
Reproduce(), however, providing a common form of reproduction for all mammals. Fish
must override Reproduce()because Fishderives directly from Animaland cannot take
OUTPUT
LISTING14.10 continued
ANALYSIS