Function Pointers and Member Function Pointers

Material on function pointers and member function pointers is available in a variety of books and online sources. We're doing a review here because it makes understanding boost::function and boost::bind much easier.

Function Pointers

Given:

We wish to declare a that can refer to any of those functions. As a practical matter, declarations include typedef. The code below creates a function pointer that takes a double as an argument and returns a double.

  1. First, we declare a function pointer using a typedef.
  2. Second, we assign a variable of type TrigFunc to the address of sin().
  3. Create an angle, \theta=\frac{\pi}{4} in radians.
  4. Use the function pointer to calculate \sin( \frac{\pi}{4})
  5. Create an array of function pointers to each of \sin(), \cos(), \tan().
  6. Invoke each of the trigonometric functions by dereferencing elements of the TrigFunc array.

Admittedly, the syntax is not, ahhh, intuitive. Don't shoot the messenger.

Member Function Pointers

What is a class? A class is data coupled with the functions that operate on that data. With this in mind, consider that C++ requires an instance pointer to use (non-static) pointers to non-static member functions. Because of the possibility of virtual member functions and the vtable (or its moral equivalent), there is no guarantee on the size of member function pointers. I've seen them range from 8bit to 128bit on different platforms. Do not assume that a fits in an int.

Tutorial Videos

[youtube="http://www.youtube.com/watch?v=AyBi6LwJrwg"]
[youtube="http://www.youtube.com/watch?v=5F0GMrx9UDA"]

One thought on “Function Pointers and Member Function Pointers

  1. Pingback: Start using boost::thread in C++ in 5 minutes | Advanced C++

Leave a Reply