Download example 2 ex2.cpp
Download header file clist2.h
Example 2 builds on example 1 and adds two new methods to the CList class. These are
void SetCallback( int (*newpointerToFunction)(pElement)) ;SetCallback has a rather messy function parameter definition as described earlier. This only allows a matching function to be passed, such as MyFunc below- matching on return type and parameter(s). The callback function has to return an int and has one parameter, a pElement.
void Process() ;
int MyFunc( pElement Element) {The other method Process traverses the list from m_head to the end of the list and calls the callback function (MyFunc()) passing in the pointer to each element. This only works of course if pointerToFunction actually has a valid function address. It is explicitly set to NULL in the class constructor.
cout << "Callback For Element "<< Element->id << " KEY=" << Element->key << endl;
return 0;
}
This code demonstrates hooking up the callback and then calling List.Process().
List.Process() ; // Does nothing as callback not yet assignedPoints to Note
List.SetCallback( MyFunc ) ;
List.Process() ;
- Easy Function declaration- Declare the function then add (* ) around the function name.
- You don't need & to get the address of a function, this is the same as an array.
- Functions must match in same number and types of parameters and the same return type but you can use void *.
- Call the function via the function pointer just like calling a function directly. eg fp(x) ;
On the next page : Other Uses of a Function Pointer

