Learn C++ - C++ Function Pointer

Declaring a Pointer to a Function

A pointer to a function has to specify to what type of function the pointer points.

The declaration should identify the function's return type and the function's argument list.

The declaration should provide the same information about a function that a function prototype does.

Suppose we have the following function.

double my_func(int);  // prototype

Here's what a declaration of an appropriate pointer type looks like:

double (*pf)(int);

pf points to a function that takes one int argument and that returns type double.

We must put the parentheses around *pf to provide the proper operator precedence.

Parentheses have a higher precedence than the * operator.

*pf(int) means pf() is a function that returns a pointer.

(*pf)(int) means pf is a pointer to a function.

After you declare pf properly, you can assign to it the address of a matching function:

double my_func(int); 
double (*pf)(int); 
pf = my_func;           // pf now points to the my_func() function 

my_func() has to match pf in both signature and return type.

Using a Pointer to Invoke a Function

(*pf) plays the same role as a function name.

We can use (*pf) as if it were a function name:

double (int); 
double (*pf)(int); 
pf = my_func;            // pf now points to the my_func() function 
double x = my_func(4);   // call my_func() using the function name 
double y = (*pf)(5);     // call my_func() using the pointer pf 


The following code demonstrates using function pointers in a program.

#include <iostream>
using namespace std;
/*w  w  w.  j a  v a2 s  . c o  m*/
double my_func(int);
void estimate(int lines, double (*pf)(int));

int main(){
    int code = 40;

    estimate(code, my_func);
    return 0;

double my_func(int lns)
    return 0.05 * lns;

void estimate(int lines, double (*pf)(int))
    cout << lines << " lines will take ";
    cout << (*pf)(lines) << " hour(s)\n";

The code above generates the following result.