< previous page page_344 next page >

Page 344
LISTING 20.10 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
48:             pDog = new Dog;
49:             (pDog->*DogFunctions[Method-1])();
50:             delete pDog;
51:          }
52:       }
53:       return 0;
54:    }

Output:
(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
Grrrrrr
(0)Quit (1)Speak (2)Move (3)Eat (4)Growl (5)Whimper (6)Roll Over
(7)Play Dead: 7
Is this 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 617, the class Dog is created, with seven member functions all sharing the same return type and signature. On line 19, a typedef declares PDF to be a pointer to a member function of Dog that takes no parameters and returns no values, and that is const: the signature of the seven member functions of Dog.
On lines 2330, the array DogFunctions is declared to hold seven such member functions, and it is initialized with the addresses of these functions.
On lines 38 and 39, the user is prompted to pick a method. Unless he picks Quit, a new Dog is created on the heap, and then the correct method is invoked on the array on line 49. Here's another good line to show to the hotshot C++ programmers in your company; ask them what this does:
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
(pDog->*DogFunctions[Method-1])();
Once again, this is a bit esoteric, but when you need a table built from member functions, it can make your program far easier to read and understand.
Summary
In this hour, you learned how to create static member variables in your class. Each class, rather than each object, has one instance of the static member variable. It is possible to access this member variable without an object of the class type by fully qualifying the name, assuming you've declared the static member to have public access.

 
< previous page page_344 next page >

If you like this book, buy it!