Special Classes and Functions 523
15
x: 2 y: 3
x: 4 y: 9
x: 64 y: 729
x: 729 y: 64
x: 531441 y:4096
On line 17, the array pFuncArrayis declared to be an array of five pointers to
functions that return void and that take two integer references.
On lines 19–31, the user is asked to pick the functions to invoke, and each member of the
array is assigned the address of the appropriate function. On lines 33–39, each function
is invoked in turn. The result is printed after each invocation.
Passing Pointers to Functions to Other Functions ........................................
The pointers to functions (and arrays of pointers to functions, for that matter) can be
passed to other functions, which can take action and then call the right function using the
pointer.
You might improve Listing 15.5, for example, by passing the chosen function pointer to
another function (outside of main()), which prints the values, invokes the function, and
then prints the values again. Listing 15.8 illustrates this variation.
LISTING15.8 Passing Pointers to Functions as Function Arguments
0: // Listing 15.8 Without function pointers
1:
2: #include <iostream>
3: using namespace std;
4:
5: void Square(int&,int&);
6: void Cube(int&, int&);
7: void Swap(int&, int &);
8: void GetVals(int&, int&);
9: void PrintVals(void (*)(int&, int&),int&, int&);
10:
11: int main()
12: {
13: int valOne=1, valTwo=2;
14: int choice;
15: bool fQuit = false;
16:
17: void (*pFunc)(int&, int&);
18:
19: while (fQuit == false)
20: {
21: cout << “(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: “;
22: cin >> choice;
ANALYSIS