< previous page page_333 next page >

Page 333
Analysis: On lines 58 four functions are declared, each with the same return type and signature, returning void and taking two references to integers.
On line 13, pFunc is declared to be a pointer to a function that returns void and takes two integer reference parameters. Any of the previous functions can be pointed to by pFunc. The user is repeatedly offered the choice of which functions to invoke, and pFunc is assigned accordingly. On lines 3436, the current value of the two integers is printed, the currently assigned function is invoked, and then the values are printed again.
Shorthand Invocation
The pointer to a function does not need to be dereferenced, although you are free to do so. Therefore, if pFunc is a pointer to a function taking an integer and returning a variable of type long, and you assign pFunc to a matching function, you can invoke that function with either
pFunc(x);
or
(*pFunc) (x);
The two forms are identical. The former is just a shorthand version of the latter.
Arrays of Pointers to Functions
Just as you can declare an array of pointers to integers, you can declare an array of pointers to functions returning a specific value type and with a specific signature. (See Listing 20.6.)
LISTING 20.6 USING AN ARRAY OF POINTERS TO FUNCTIONS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:     // Listing 20.6 demonstrates use of an array of pointers to functions
2:
3:     #include <iostream.h>
4:
5:     void Square (int&,int&);
6:     void Cube (int&, int&);
7:     void Swap (int&, int &);
8:     void GetVals(int&, int&);
9:     void PrintVals(int, int);
10:
11:    int main()
12:    {
13:       int valOne=1, valTwo=2;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_333 next page >

If you like this book, buy it!