C/C++ Programming: Pointers to functions

Pointers to functionsEvery C/C++ programmer knows what pointer ( * ) is. Pointer is a integral part of C/C++ programming. I think pointer adds spice to C/C++. Without pointer C/C++ programming will be dull as programing in Visual Basic, or Java, or ASP/HTML/ColdFusion/PHP ( Are they even programming languagues/ oh they r scripts, how dull !!! ).

Anyways, Lets talk about Pointers to functions.Data isn't the only thing you can have a pointer to. You can also have a pointer to a function. Function pointers allow you to use functions during run time that you either didn't have available during development or that you aren't sure of the order in which the functions should be called.

TypedefFunction pointers are a bit more complicated in that they aren't a predefined type. They don't have a predefined size nor do they have a specific set of inputs or outputs. So before we can cast a pointer as a function type, we have to declare the function inputs and outputs. We do this using typedef:

typedef int (*Function_Pointer_Type)(int);

Notice the asterisk in front of the variable type name Function_Pointer. This means that whatever we cast with this new type, it is already a pointer. The inputs and outputs of this function are 'int's. These inputs and outputs are sometimes referred to as a function's "signature". Here is an example of a function that has the same signature as the above function type:

int Square(int num){ return num * num;}

AssignThe name of the function itself gives us a pointer to it. All we have to do is leave off the parenthesis ()'s like so:

Funtion_Pointer_Type function_pointer; //Already a pointer, remember?function_pointer = Square; //Leave off the ()'s and it's a pointer to the function

int output = function_pointer(4); //use the pointer like the function!

Class Member FunctionsYou can also get pointers to class member functions this way too. However, in order to get a pointer to those functions, they must be declared static in the class definition. Unfortunately, declaring class member functions static prevents accessing the other class members.

class foo{public: foo(); //Construct is private so no one outside the class can call it static int Square(int num); //Static class member functions can pass pointers int Add(int num); //Non static member functions will not give out it's pointer}