Sams Teach Yourself C++ in 21 Days

(singke) #1
40: {
41: fQuit = true;
42: }
43: else
44: {
45: pDog = new Dog;
46: (pDog->*DogFunctions[Method-1])();
47: delete pDog;
48: }
49: }
50: return 0;
51: }

(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Roll Over
➥(7)Play Dead: 1
Woof!
(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Roll Over
➥(7)Play Dead: 4
Grrr
(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Roll Over
➥(7)Play Dead: 7
The end of Little Caesar?
(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Roll Over
➥(7)Play Dead: 0
On lines 5–15, the class Dogis created, with seven member functions all sharing
the same return type and signature. On line 17, a typedefdeclares PDFto be a
pointer to a member function of Dogthat takes no parameters and returns no values, and
that is const: the signature of the seven member functions of Dog.
On lines 21–28, the array DogFunctionsis declared to hold seven such member func-
tions, and it is initialized with the addresses of these functions.
On lines 36 and 37, the user is prompted to pick a method. Unless Quitis picked, a new
Dogis created on the heap, and then the correct method is invoked on the array on line


  1. Here’s another good line to show to the hotshot C++ programmers in your company;
    ask them what this does:
    (pDog->*DogFunctions[Method-1])();
    You’ll be able to tell the hotshot that it is a call to a method in an object using a pointer
    stored to the method that is stored in an array at the offset of Method-1.
    Once again, this is a technique that should be avoided whenever possible. If it must be
    used, document it extensively and try to think of another way to accomplish the desired
    task.


OUTPUT


532 Day 15


LISTING15.11 continued

ANALYSIS
Free download pdf