C++ Basics [08]: Pointers to Functions

2 minute read

Published:

A function pointer is a pointer that denotes a function rather than an object. Like any other pointer, a function pointer points to a particular type. A function’s type is determined by its return type and the types of its parameters.


Using Function Pointers

A function pointer has the form:

type (*pf)(parameterList)

Suppose the following function is defined:

int Sum(int a, int b){
    return a + b;
}

When we use the name of a function as a value, the function is automatically converted to a pointer. Hence, a function pointer can be defined in one of the following ways:

int (*pf)(int, int) = Sum;
int (*pf)(int, int) = ∑

Then, we can use a pointer to a function to call the function just like the function itself, and there is no need to dereference the pointer.

int sum1 = pf(3, 4);    // 7
int sum2 = (*pf)(3, 4); // 7
int sum3 = Sum(3, 4);   // 7

When we use pointers to overloaded functions, the context must make it clear which version is being used.

void ff(int*);
void ff(unsigned int);
void (*pf1)(unsigned int) = ff; // pf1 points to ff(unsigned)
void (*pf2)(int) = ff;          // error: no ff with a matching parameter list
double (*pf3)(int*) = ff;       // error: return type of ff and pf3 don't match

Passing a Function Pointer to a Function

Passing a function pointer to a function has the form:

funcType funcName(funcParameterList, funcPointerType (*pf)(funcPointerParameterList));

Just as with arrays, we cannot define parameters of function type but can have a parameter that is a pointer to function.

int getSum(int a, int b, int (*pf)(int, int)){
    return pf(a, b);
}
// or 
int getSum(int a, int b, int pf(int, int)) {
    return pf(a, b);
}
// or 
typedef bool(*FuncP)(const string&, const string&);
typedef decltype(lengthCompare) *FuncP; // equivalent type
int getSum(int a, int b, FuncP) {
    return pf(a, b);
}

We can use one of the following ways to call the function.

getSum(3, 4, pf);      // 7
getSum(3, 4, *pf);     // 7
getSum(3, 4, Sum);     // 7

Returning a Functions Pointer From a Function

Returning a function pointer from a function has the form:

funcPointerType (*funcName(funcParameterList))((funcPointerParameterList));

As with arrays, we can’t return a function type but can return a pointer to a function type.

int (*getSum())(int, int){
    return pf;
}

To simplify the declaration, we can use a type alias:

using F = int (int*, int);       // F is a function type, not a pointer
using PF = int (*)(int*, int);   // PF is a pointer type
PF getSum();
F *getSum();

We can also declare the function using a trailing return:

auto getSum() -> int (*)(int, int);

Table of Contents

Comments