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

C++ Tutorial - Advanced Pointers

By David Bolton, About.com

5 of 8

Learn About Function Pointers

Function Pointers

What exactly is a function pointer? Just what it says; a pointer to any function that you have defined or linked and wish to call indirectly. The point is that you call functions and they do something. But instead of calling a function directly as we've done so far, it is called indirectly via a pointer. This can be changed at runtime, as long as the desired function matches the required signature. Matching means that it must have the same return type and the same number and types of parameters. Fortunately void * matches most pointer types so this gives a little more flexibility.

Where would you use a Function pointer? Well anywhere where you don't want to hard code just one function. Take example one. What if we wanted to process every item in this list with a particular function. Because the internals of the list are private inside the class we cannot write a loop and process each dataElement. Instead we need a different approach.

Here is how we do it. First we declare a variable that will hold the function pointer. This is the slightly messy bit.

int (*pointerToFunction) (pElement) = NULL ;
Note that the *pointerToFunction is within brackets. Without the brackets you'd have a function that returned a pointer to an int. Just remember- the *pointertofunction must be in brackets. To the left you have the return result and to the right the parameters, the assignment = and the NULL. It's just like a normal function declaration except that it is a variable and you assign it 0 or NULL or the name of a matching function.

On the next page : An example with Function Pointers

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. Learn About Function Pointers

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

All rights reserved.