What is a Function Pointer ?

Function Pointers are pointers, i.e. variables, which point to the address of a function. Executing a program gets a certain space in the main-memory. Both, the executable compiled program code
and the used data variables, are put inside this memory. Thus a function in the program code is, like e.g. a character field, nothing else than an address.


// define a function pointer and initialize to NULL

int (*pt2Function)(float, char, char) = NULL; // C
int (MyClass::*pt2Member)(float, char, char) = NULL; // C++
int (MyClass::*pt2ConstMember)(float, char, char) const = NULL; // C++

To these pointers on can assign the address of functions matching with the similar signatures

Function Pointers provide some extremely interesting, efficient and elegant programming techniques. You can use them to replace switch/if-statements, to realize your own late-binding or to implement callbacks. Due to their complicated syntax – they are treated quite stepmotherly in most computer books and documentations. If at all, they are addressed quite briefly and superficially. They are less error prone than normal pointers cause you will never allocate or de-allocate memory with them. All you’ve got to do is to understand what they are and to learn their syntax. But keep in mind: Always ask yourself if you really need a function pointer. It’s nice to realize one’s own late-binding but to use the existing structures of C++
may make your code more readable and clear.

One aspect in the case of late-binding is runtime: If you call a virtual function, your program has got to determine which one has got to be called. It does this using a V-Table containing all the possible functions. This costs some time each call and maybe you can save some time using function pointers instead of virtual functions.

No comments: