C++: Function Pointers

Function Pointers

In this C++ video, we cover the topic of function pointers. Function pointers allow us to call many different functions through the same function pointer interface. Interfaces are an object-oriented concept, which we have not covered yet. However, function pointers are a stepping-stone to the object-oriented concept of interfaces.

Function pointers came from C and are used far less often in C++ because they have largely been superseded by other elements of C++. However, there are still some situations where function pointers are convenient, even in C++. Moreover, many libraries like GLUT, which we use for GUI development in our OpenGL lessons, use function pointers extensively.

  • Dereference
    • pfnFunctPtr();
    • (*pfnFunctPtr)();
  • Assignment
    • pfnFunctPtr = Function();
    • pfnFunctPtr = &Function;
  • No Pointer Arithmetic allowed:
    • ++pfnFunctPtr;
    • pfnFunctPtr++;
    • pfnFunctPtr = pfnFunctPtr + 5;

The syntax above shows some of the differences between function pointers and ordinary data pointers. For example, we can dereference a function pointer with or without the asterisk--although we will typically favor not using the asterisk because it is cleaner looking. Likewise, we can assign a function pointer with or without the address-of operator. Again, we will tend to make assignments without the address-of operator. Function pointers give us these options, whereas we need to use the dereference and address-of operators for data pointers. Finally, we cannot use pointer arithmetic on function pointers: increment, decrement, and adding integers.

#include <iostream>
#include <cmath>

int main() {
    using namespace std;

    double (*pfnMathFn[3])(double) = {sin, sqrt, abs};

    cout << pfnMathFn[0](3.14159/2) << endl;
    cout << pfnMathFn[1](9.0) << endl;
    cout << pfnMathFn[2](-1.4) << endl;

    return 0;
}

Above, we have a simple example of an array of three function pointers. There function pointers take in a single double argument and return a double. In our declaration, we assign these function pointers to the sine, the square root, and the absolute value functions, respectively. Then we call each of these functions and output the results. Below is the output of the program.

The syntax for function pointers can get confusing, especially when we use arrays of function pointers, pointers to function pointers, etc. In the coming lessons, we will develop ways to simplify this syntax and cleaner mechanisms for doing the types of things that we would use function pointers for.