< previous page page_268 next page >

Page 268
C++ extends its polymorphism to allow pointers to base classes to be assigned to derived class objects. Therefore, you can write
Mammal* pMammal = new Dog;
This creates a new Dog object on the heap and returns a pointer to that object, which it assigns to a pointer to Mammal. This is fine, because a Dog is a Mammal.
This is the essence of polymorphism. You could, for example, create many different types of windowsincluding dialog boxes, scrollable windows, and list boxesand give them each a virtual draw() method. By creating a pointer to window and assigning dialog boxes and other derived types to that pointer, you can call draw() without regard to the actual runtime type of the object pointed to. The correct draw() function will be called.

You can then use this pointer to invoke any method on Mammal. What you would like is for those methods that are overridden in Dog to call the correct function. Virtual member functions let you do that. Listing 17.1 illustrates how this works, and what happens with non-virtual methods.
LISTING 17.1 USING VIRTUAL METHODS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:    //Listing 17.1 Using virtual methods
2:
3:    #include <iostream.h>
4:
5:    class Mammal
6:    {
7:    public:
8:       Mammal():itsAge(1) { cout << Mammal constructor\n; }
9:       ~Mammal() { cout << Mammal destructor\n; }
10:      void Move() const { cout << Mammal move one step\n; }
11:      virtual void Speak() const { cout << Mammal speak!\n; }
12:   protected:
13:      int itsAge;
14:
15:   };
16:
17:   class Dog : public Mammal
18:   {
19:   public:
20:      Dog() { cout << Dog constructor\n; }
21:      ~Dog() { cout << Dog destructor\n; }
22:      void WagTail()const { cout << Wagging Tail\n; }
23:      void Speak()const { cout << Woof!\n; }
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_268 next page >

If you like this book, buy it!