Sams Teach Yourself C++ in 21 Days

(singke) #1
Special Classes and Functions 517

15


functions can be pointed to by pFunc. The user is repeatedly offered the choice of which
functions to invoke, and pFuncis assigned accordingly. On lines 33–35, the current value
of the two integers is printed, the currently assigned function is invoked, and then the
values are printed again.

Pointer to Function
A pointer to function is invoked the same as the functions it points to, except that the
function pointer name is used instead of the function name.
Assign a pointer to function to a specific function by assigning to the function name with-
out the parentheses. The function name is a constant pointer to the function itself. Use
the pointer to function the same as you would the function name. The pointer to func-
tion must agree in return value and signature with the function to which you assign it.
Example
long (*pFuncOne) (int, int);
long SomeFunction (int, int);
pFuncOne = SomeFunction;
pFuncOne(5,7);

Be aware that pointers to functions can be highly dangerous. You can acci-
dentally assign to a function pointer when you want to call the function, or
you can accidentally call the function when you want to assign to its pointer.

CAUTION


Why Use Function Pointers?..........................................................................


Generally, you shouldn’t use function pointers. Function pointers date from the days of
C, before object-oriented programming was available. They were provided to allow for a
programming style that had some of the virtues of object orientation; however, if you are
writing a program that is highly dynamic and needs to operate different functionality
based on runtime decisions, this can be a viable solution.
You certainly could write a program like Listing 15.5 without function pointers, but the
use of these pointers makes the intent and use of the program explicit: Pick a function
from a list, and then invoke it.
Listing 15.6 uses the function prototypes and definitions from Listing 15.5, but the body
of the program does not use a function pointer. Examine the differences between these
two listings.
Free download pdf