< previous page page_284 next page >

Page 284
At runtime, the base pointer will be examined. If the conversion is proper, your new Cat pointer will be fine. If the conversion is improper, if you didn't really have a Cat object after all, your new pointer will be null. Listing 18.2 illustrates this.
LISTING 18.2 DYNAMIC CAST

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:   // Listing 18.2 - dynamic cast
2:
3:   #include <iostream.h>
4:   class Mammal
5:   {
6:   public:
7:      Mammal():itsAge(1) { cout << Mammal constructor\n; }
8:      virtual ~Mammal() { cout << Mammal destructor\n; }
9:      virtual void Speak() const { cout << Mammal speak!\n; }
10:   protected:
11:      int itsAge;
12:   };
13:
14:  class Cat: public Mammal
15:  {
16:  public:
17:     Cat() { cout << Cat constructor\n; }
18:     ~Cat() { cout << Cat destructor\n; }
19:     void Speak()const { cout << Meow\n; }
20:     void Purr() const { cout << rrrrrrrrrrr\n; }
21:  };
22:
23:  class Dog: public Mammal
24:  {
25:  public:
26:     Dog() { cout << Dog Constructor\n; }
27:     ~Dog() { cout << Dog destructor\n; }
28:     void Speak()const { cout << Woof!\n; }
29:  };
30:
31:
32:  int main()
33:  {
34:     const int NumberMammals = 3;
35:     Mammal* Zoo[NumberMammals];
36:     Mammal* pMammal;
37:     int choice,i;
38:     for (i=0; i<NumberMammals; i++)
39:     {
40:        cout << (1)Dog (2)Cat: ;
41:        cin >> choice;
42:        if (choice == 1)
43:           pMammal = new Dog;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_284 next page >

If you like this book, buy it!