POINTERS TO FUNCTIONS

A pointer stores an address value that, up to now, has been the address of another variable. This has provided considerable flexibility in allowing you 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, the pointer must also maintain information about the parameter list for the function it points to, as well as the return type. Therefore, the type for a pointer to a function must incorporate the parameter types and the return type of the functions to which it can point. 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, you can only store the address of a function that has exactly this form. If you want to store the address of a function that accepts two arguments of type int and returns type char, you must define another pointer with a type that includes these characteristics.

Declaring Pointers to Functions

You can declare a pointer pfun that you can use to point to functions that take two arguments, of type char* and int, and return a value of type double like this:

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.