1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Advanced Pointers

By David Bolton, About.com

6 of 8

An Example with Function Pointers

In Example 2, we use a function pointer to create a callback function. This is a function that is called for every element in the list. Make sure you code it so that if no callback function is hooked up then nothing nasty happens.

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)) ;
void Process() ;
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.

int MyFunc( pElement Element) {
  cout << "Callback For Element "<< Element->id << " KEY=" << Element->key << endl;
  return 0;
}
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.

This code demonstrates hooking up the callback and then calling List.Process().

List.Process() ; // Does nothing as callback not yet assigned
List.SetCallback( MyFunc ) ;
List.Process() ;
Points to Note
  • 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

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. An Example with Function Pointers

©2009 About.com, a part of The New York Times Company.

All rights reserved.