< previous page page_340 next page >

Page 340
Pointers to Member Functions
Up until this point, all the function pointers you've created have been for general, non-class functions. It is also possible to create pointers to functions that are members of classes.
To create a pointer to member function, use the same syntax as with a pointer to a function, but include the class name and the scoping operator (::). Thus, if pFunc points to a member function of the class Shape, which takes two integers and returns void, the declaration for pFunc is the following:
void (Shape::*pFunc) (int, int);
Pointers to member functions are used in exactly the same way as pointers to functions, except that they require an object of the correct class on which to invoke them. Listing 20.9 illustrates the use of pointers to member functions.
Some compilers do not support the use of a function name as a synonym for its address. If your compiler gives you a warning or error with this listing, try changing lines 67 and 68 to
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
67:              case 1: pFunc = & Mammal::Speak; break;
68:              default: pFunc = & Mammal::Move; break;
and then make the same change on all subsequent listings. (Note addition of ampersand (&) on each line.)

LISTING 20.9 POINTERS TO MEMBER FUNCTIONS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:     //Listing 20.9 Pointers to member functions
2:
3:     #include <iostream.h>
4:
5:     class Mammal
6:     {
7:     public:
8:        Mammal():itsAge(1) { }
9:       virtual ~Mammal() {}
10:       virtual void Speak() const = 0;
11:       virtual void Move() const = 0;
12:    protected:
13:       int itsAge;
14:    };
15:
16:    class Dog : public Mammal
17:    {
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_340 next page >

If you like this book, buy it!