Dirk Bertels

The greatest malfunction of spirit
is to believe things (Louis Pasteur)

Function Pointers in C and C++

Function pointers in C

Function pointers are just code pointers, holding the starting address of an assembly language routine. In C, type safe pointers to functions can be created and stored just like any other pointer.

They are mostly used as parameters to library functions and callbacks for windows functions.

The classic function pointer declaration in C takes on the following form:

float(*myFnPtr)(int, char *);  // function pointer declaration

As funtion pointers can get confusing, especially when used as parameters, it is better to use a typedef:

typedef float(*MyFnPtrType)(int, char *);
MyFnPtrType myFnPtr;		

To make this function pointer point to a function:

float someFn(int, char *);      // the function pointed to
myFnPtr = someFn;               // allocate function pointer to this function
(*myFnPtr)(7, "some string");   // invoke the function pointer

C++ Member Function Pointers

In C++ most functions are member functions because they are part of a class. The primary use of member function pointers is in delegates. For more on delegates in managed C++, see Delegate mechanism.

There are some exceptions: They don't work for static member functions (which require 'normal' C function pointers), and they don't work on inherited classes. The syntax for member function pointers in C++ is as follows:

float (SomeClass::*myMembFnPtr)(int, char *);   // member function pointer declaration
float SomeClass::someMembFn(int, char *);       // the function pointed to
myMembFnPtr = &SomeClass::someMembFn;           // allocate function pointer to this function
SomeClass *s = new SomeClass;                   // create an instance of the class
(s->*myMembFnPtr)(6, "some string");             // invoke the member function pointer
// if your class is on the stack, use	
(s.*myMembFnPtr)(6, "some string");