62: cin >> Method;
63: switch (Method)
64: {
65: case 1: pFunc = Mammal::Speak; break;
66: default: pFunc = Mammal::Move; break;
67: }
68:
69: (ptr->*pFunc)();
70: delete ptr;
71: }
72: }
73: return 0;
74: }
(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
On lines 5–14, the abstract class Mammalis declared with two pure virtual meth-
ods:Speak()and Move(). Mammalis subclassed into Dog,Cat, and Horse, each of
which overrides Speak()and Move().
The driver program in main()starts on line 40. On line 50, the user is asked to choose
the type of animal to create. Based on this selection, a new subclass of Animalis created
on the free store and assigned to ptron lines 54–56.
On line 61, the user is given a second prompt asking him to select the method to invoke.
The method selected, either Speakor Move, is assigned to the pointer pFuncon lines
65–66. On line 69, the method chosen is invoked by the object created, by using the
pointer ptrto access the object and pFuncto access the function.
Finally, on line 70,deleteis called on the pointer ptrto return the memory set aside for
the object to the free store. Note that no reason exists to call delete on pFuncbecause this
is a pointer to code, not to an object on the free store. In fact, attempting to do so gener-
ates a compile-time error.
OUTPUT
530 Day 15
LISTING15.10 continued
ANALYSIS