Pointers to Functions ..........................................................................................
Just as an array name is a constant pointer to the first element of the array, a function
name is a constant pointer to the function. It is possible to declare a pointer variable that
points to a function and to invoke the function by using that pointer. This can be very
useful; it enables you to create programs that decide which functions to invoke based on
user input.
The only tricky part about function pointers is understanding the type of the object being
pointed to. A pointer to intpoints to an integer variable, and a pointer to a function must
point to a function of the appropriate return type and signature.
In the declaration
long (* funcPtr) (int);
funcPtris declared to be a pointer (note the *in front of the name) that points to a func-
tion that takes an integer parameter and returns a long. The parentheses around *
funcPtrare necessary because the parentheses around intbind more tightly; that is,
they have higher precedence than the indirection operator (*). Without the first parenthe-
ses, this would declare a function that takes an integer and returns a pointer to a long.
(Remember that spaces are meaningless here.)
Examine these two declarations:
long * Function (int);
long (* funcPtr) (int);
The first,Function (), is a function taking an integer and returning a pointer to a vari-
able of type long. The second,funcPtr, is a pointer to a function taking an integer and
returning a variable of type long.
The declaration of a function pointer will always include the return type and the paren-
theses indicating the type of the parameters, if any. Listing 15.5 illustrates the declaration
and use of function pointers.
LISTING15.5 Pointers to Functions
0: // Listing 15.5 Using function pointers
1:
2: #include <iostream>
3: using namespace std;
4:
5: void Square (int&,int&);
6: void Cube (int&, int&);
514 Day 15