< previous page page_342 next page >

Page 342
LISTING 20.9 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
67:             default: pFunc = Mammal::Move; break;
68:          }
69:
70:          (ptr->*pFunc)();
71:          delete ptr;
72:       }
73:     return 0;
74:    }

Output:
(0)Quit (1)Dog (2)Cat (3)Horse: 1
(1)Speak (2)Move: 1
Woof!
(0)Quit (1)Dog (2)Cat (3)Horse: 2
(1)Speak (2)Move: 1
Meow!
(0)Quit (1)Dog (2)Cat (3)Horse: 3
(1)Speak (2)Move: 2
Galloping
(0)Quit (1)Dog (2)Cat (3)Horse: 0
Analysis: On lines 514, the abstract data type Mammal is declared with two pure virtual methods, Speak() and Move(). Mammal is subclassed into Dog, Cat, and Horse, each of which overrides Speak() and Move().
The driver program in main() asks the user to choose which type of animal to create, and then a new subclass of Animal is created on the free store and assigned to ptr on lines 5456.
The user is then prompted for which method to invoke, and that method is assigned to the pointer pFunc. On line 70, the method chosen is invoked by the object created, by using the pointer ptr to access the object and pFunc to access the function.
Finally, on line 71, delete is called on the pointer ptr to return the memory set aside for the object to the free store. Note that there is no reason to call delete on pFunc because this is a pointer to code, not to an object on the free store. In fact, attempting to do so will generate a compile-time error.
Arrays of Pointers to Member Functions
As with pointers to functions, pointers to member functions can be stored in an array. The array can be initialized with the addresses of various member functions, and those can be invoked by offsets into the array. Listing 20.10 illustrates this technique.

 
< previous page page_342 next page >

If you like this book, buy it!