Sams Teach Yourself C++ in 21 Days

(singke) #1

454 Day 14


3: #include <iostream>
4: using namespace std;
5:
6: enum TYPE { HORSE, PEGASUS };
7:
8: class Horse
9: {
10: public:
11: virtual void Gallop(){ cout << “Galloping...\n”; }
12:
13: private:
14: int itsAge;
15: };
16:
17: class Pegasus : public Horse
18: {
19: public:
20: virtual void Fly()
21: {cout<<”I can fly! I can fly! I can fly!\n”;}
22: };
23:
24: const int NumberHorses = 5;
25: int main()
26: {
27: Horse* Ranch[NumberHorses];
28: Horse* pHorse;
29: int choice,i;
30: for (i=0; i<NumberHorses; i++)
31: {
32: cout << “(1)Horse (2)Pegasus: “;
33: cin >> choice;
34: if (choice == 2)
35: pHorse = new Pegasus;
36: else
37: pHorse = new Horse;
38: Ranch[i] = pHorse;
39: }
40: cout << endl;
41: for (i=0; i<NumberHorses; i++)
42: {
43: Pegasus *pPeg = dynamic_cast< Pegasus *> (Ranch[i]);
44: if (pPeg != NULL)
45: pPeg->Fly();
46: else
47: cout << “Just a horse\n”;
48:
49: delete Ranch[i];
50: }
51: return 0;
52: }

LISTING14.2 continued
Free download pdf