Wrox Press C++ Tutorial
A pointer stores an address value which, up to now, has been the address of another variable with the same basic type as the pointer. This has provided considerable flexibility in allowing us to use different variables at different times through a single pointer. A pointer can also point to the address of a function. This enables you to call a function through a pointer, which will be the function at the address that was last assigned to the pointer.
Obviously, a pointer to a function must contain the memory address of the function that you want to call. To work properly, however, the pointer must also maintain information about the parameter list for the function it points to, as well as the return type. Therefore, when you declare a pointer to a function, you have to specify the parameter types and the return type of the functions that it can point to, in addition to the name of the pointer. Clearly, this is going to restrict what you can store in a particular pointer to a function. If you have declared a pointer to functions that accept one argument of type int and return a value of type double, then you can only store the address of a function that has exactly the same form. If you want to store the address of a function that accepts two arguments of type int and returns type char, then you must define another pointer with these characteristics.
Let's declare a pointer pfun that we can use to point to functions that take two arguments of type char* and int, and return a value of type double. The declaration would be as follows:
double (*pfun)(char*, int); // Pointer to function declaration
The parentheses may make this look a little weird at first. This declares a pointer, pfun, which can point to functions which accept two arguments of type pointer to char and of type int, and which return a value of type double. The parentheses around the pointer name, pfun, and the asterisk, are necessary: without them, it would be a function declaration rather than a pointer declaration. In this case, it would look like this:
double *pfun(char*, int); // Prototype for a function
// returning type double*
This is a prototype for a function pfun() which has two parameters, and returns a pointer to a double value. Since we were looking to declare a pointer, this is clearly not what we want at the moment.
The general form of a declaration of a pointer to a function is given here:
return_type (*pointer_name)(list_of_parameter_types);
The pointer can only point to functions with the same return_type and list_of_parameter_types specified in the declaration.
This shows that the declaration breaks down into three components:
If you attempt to assign a function to a pointer that does not conform to the types in the pointer declaration, the compiler generates an error message.
You can initialize a pointer to a function with the name of a function within the declaration of the pointer. This is what it might look like:
// Function prototype
long sum(long num1, long num2);
// Pointer to function points to sum()
long (*pfun)(long, long) = sum;
Here, the pointer can be set to point to any function that accepts two arguments of type long, and also returns a value of type long.
Of course, you can also initialize a pointer to a function by using an assignment statement. Assuming the pointer pfun has been declared as above, we could set the value of the pointer to a different function with these statements:
long product(long, long); // Function prototype
...
pfun = product; // Set pointer to function product()
As with pointers to variables, you must ensure that a pointer to a function is initialized before you use it to call a function. Without initialization, catastrophic failure of your program is guaranteed.
To get a proper feel for these newfangled pointers and how they perform in action, let's try one out in a program:
// Ex5_01.cpp
// Exercising pointers to functions
#include <iostream>
using namespace std;
long sum(long a, long b); // Function prototype
long product(long a, long b); // Function prototype
int main()
{
// Pointer to function declaration
long (*pdo_it)(long, long);
pdo_it = product;
cout << endl
// Call product thru a pointer
<< "3*5 = " << pdo_it(3, 5);
pdo_it = sum; // Reassign pointer to sum()
cout << endl
<< "3*(4+5) + 6 = "
// Call thru a pointer twice
<< pdo_it(product(3, pdo_it(4, 5)), 6);
cout << endl;
return 0;
}
// Function to multiply two values
long product(long a, long b)
{
return a*b;
}
// Function to add two values
long sum(long a, long b)
{
return a+b;
}
This is hardly a useful program, but it does show very simply how a pointer to a function is declared, assigned a value and subsequently used to call a function.
After the usual preamble, we declare a pointer to a function, pdo_it, which can point to either of the other two functions that we have defined, sum() or product(). The pointer is given the address of the function product() in this assignment statement:
pdo_it = product;
When initializing an ordinary pointer, the name of the function is used in a similar way to that of an array name in that no parentheses or other adornments are required. The function name is automatically converted to an address which is stored in the pointer.
The function product() is then called indirectly through the pointer pdo_it in the output statement.
cout << endl
// Call product thru a pointer
<< "3*5 = " << pdo_it(3, 5);
The name of the pointer is used just as if it were a function name, and is followed by the arguments between parentheses exactly as they would appear if the original function name were being used directly.
Just to show that we can do it, we change the pointer to point to the function sum(). We then use it again in a ludicrously convoluted expression to do some simple arithmetic. This shows that a pointer to a function can be used in exactly the same way as the function that it points to. The sequence of actions in the expression is shown here:
Since 'pointer to a function' is a perfectly reasonable type, a function can also have a parameter that is a pointer to a function. The function can then call the function pointed to by the argument. Since the pointer can be made to point at different functions in different circumstances, this allows the particular function that is to be called from inside a function to be determined in the calling program. In this case, you can pass a function explicitly as an argument.
We can look at this with an example. Suppose we need a function that will process an array of numbers by producing the sum of the squares of each of the numbers on some occasions, and the sum of the cubes on other occasions. One way of achieving this is by using a pointer to a function as an argument.
//Ex5_02.cpp
// A pointer to a function as an argument
#include <iostream>
using namespace std;
// Function prototypes
double squared(double);
double cubed(double);
double sumarray(double array[], int len, double (*pfun)(double));
int main()
{
double array[] = { 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5 };
int len = sizeof array/sizeof array[0];
cout << endl
<< "Sum of squares = "
<< sumarray(array,len,squared);
cout << endl
<< "Sum of cubes = "
<< sumarray(array,len,cubed);
cout << endl;
return 0;
}
// Function for a square of a value
double squared(double x)
{
return x*x;
}
// Function for a cube of a value
double cubed(double x)
{
return x*x*x;
}
// Function to sum functions of array elements
double sumarray(double array[], int len, double (*pfun)(double))
{
double total = 0.0; // Accumulate total in here
for(int i=0; i<len; i++)
total += pfun(array[i]);
return total;
}
If you compile and run this code, you should see the following output:

The first statement of interest is the prototype for the function sumarray(). Its third parameter is a pointer to a function which has a parameter of type double, and returns a value of type double.
double sumarray(double array[], int len, double (*pfun)(double));
The function sumarray() processes each element of the array passed as its first argument with whatever function is pointed to by its third argument. The function then returns the sum of the processed array elements.
We call the function sumarray() twice in main(), the first time with squared as the third argument, and the second time using cubed. In each case, the address corresponding to the function name used as an argument, will be substituted for the function pointer in the body of the function sumarray(), so the appropriate function will be called within the for loop.
There are obviously easier ways of achieving what this example does, but using a pointer to a function provides you with a lot of generality. You could pass any function to sumarray() that you care to define as long as it takes one double argument and returns a value of type double.
In the same way as regular pointers, you can declare an array of pointers to functions. You can also initialize them in the declaration. An example of declaring an array of pointers would be:
double sum(double, double); // Function prototype
double product(double, double); // Function prototype
double difference(double, double); // Function prototype
// Array of function pointers
double (*pfun[3])(double,double) = { sum, product, difference };
Each of the elements in the array is initialized by the corresponding function address appearing in the initializing list between braces. To call the function product() using the second element of the pointer array, you would write:
pfun[1](2.5, 3.5);
The square brackets which select the function pointer array element appear immediately after the array name and before the arguments to the function being called. Of course, you can place a function call through an element of a function pointer array in any appropriate expression in which the original function might legitimately appear, and the index value selecting the pointer can be any expression producing a valid index value.