Polymorphism 451
14
9: void Gallop(){ cout << “Galloping...\n”; }
10: virtual void Fly() { cout << “Horses can’t fly.\n” ; }
11: private:
12: int itsAge;
13: };
14:
15: class Pegasus : public Horse
16: {
17: public:
18: virtual void Fly()
19: {cout<<”I can fly! I can fly! I can fly!\n”;}
20: };
21:
22: const int NumberHorses = 5;
23: int main()
24: {
25: Horse* Ranch[NumberHorses];
26: Horse* pHorse;
27: int choice,i;
28: for (i=0; i<NumberHorses; i++)
29: {
30: cout << “(1)Horse (2)Pegasus: “;
31: cin >> choice;
32: if (choice == 2)
33: pHorse = new Pegasus;
34: else
35: pHorse = new Horse;
36: Ranch[i] = pHorse;
37: }
38: cout << endl;
39: for (i=0; i<NumberHorses; i++)
40: {
41: Ranch[i]->Fly();
42: delete Ranch[i];
43: }
44: return 0;
45: }
(1)Horse (2)Pegasus: 1
(1)Horse (2)Pegasus: 2
(1)Horse (2)Pegasus: 1
(1)Horse (2)Pegasus: 2
(1)Horse (2)Pegasus: 1
Horses can’t fly.
I can fly! I can fly! I can fly!
Horses can’t fly.
I can fly! I can fly! I can fly!
Horses can’t fly.
OUTPUT
LISTING14.1 continued