Pointers to Functions in C++ - dummies

By John Paul Mueller, Jeff Cogswell

When an application is running, the functions in the application exist in the memory; so just like anything else in memory, they have an address. And having an address is good, because that way, people can find you.

You can take the address of a function by taking the name of it and putting the address-of operator (&) in front of the function name, like this:

address = &MyFunction;

But to make this work, you need to know what type to declare address. The address variable is a pointer to a function, and the cleanest way to assign a type is to use a typedef. (Fortunately, this is one time when most people are willing to use a typedef.)

Here’s the typedef, believe it or not:

typedef int(*FunctionPtr)(int);

It’s hard to follow, but the name of the new type is FunctionPtr. This defines a type called FunctionPtr that returns an integer (the leftmost int) and takes an integer as a parameter (the rightmost int, which must be in parentheses).

The middle part of this statement is the name of the new type, and you must precede it by an asterisk, which means that it’s a pointer to all the rest of the expression. Also, you must put the type name and its preceding asterisk inside parentheses.

And then you’re ready to declare some variables! Here goes:

FunctionPtr address = &MyFunction;

This line declares address as a pointer to a function and initializes it to MyFunction(). Now, for this to work, the code for MyFunction() must have the same prototype declared in the typedef: In this case, it must take an integer as a parameter and return an integer.

So, for example, you may have a function like this:

int TheSecretNumber(int x) {
    return x + 1;
}

Then you could have a main() that stores the address of this function in a variable — and then calls the function by using the variable:

int main(int argc, char *argv[])
{
    typedef int (*FunctionPtr)(int);
    int MyPasscode = 20;
    FunctionPtr address = &TheSecretNumber;
    cout << address(MyPasscode) << endl;
}

Now, just so you can say that you’ve seen it, here’s what the address declaration would look like without using a typedef:

int (*address)(int) = &TheSecretNumber;

The giveaway should be that you have two things in parentheses side by side, and the set on the right has only types inside it. The one on the left has a variable name. So this line is not declaring a type; rather, it’s declaring a variable.