Function Pointers

Function pointers are just like any other type of pointer within C/C++, in that they point to a reference in memory to something that is the reference to the object (a pointer to a integer type that is holding the value 2 is the value of 2 and the pointer just points to this object). Since a pointer can point to any type of object that is similar to the object type, you can also have pointers to functions. This type of pointer is good for having a single function pointer to list of functions that is chosen from a action, for example if there was a list of function for the edit action within the standard document editors (Cut/Copy/Paste/Undo/Redo) and to just point to within every function was required was to use the drop down list item number, then the code is very small and also re-usable.

For example of code with using function pointers.

#include <iostream>
using namespace std;
void f()
       cout << "hi" << endl;       
void g()
       cout << "bye" << endl;
// always set the function pointer to NULL.
void (*func)() = NULL;
// to pass a function pointer to a function.
void callFunc( void (*function)())
int main(int argc, char* argv[])
       // set the func object (as created above – void (*func)() = NULL; - to the function address f)
       // call the function that is assoicated with the func pointer
       // reset to another function.
       // call the function pointed to within another function.
       return 0;

I have included Microsoft Visual Studio 2005 downloadable edition (here) and also Linux code for this tutorial as a download.

Leave a Reply

Your email address will not be published. Required fields are marked *