Introduction To Function Pointers
What are Function Pointers?
- Function pointers are pointers – Variables – which point to the address of a function.
- Actually Function pointers provide some extremely interesting, efficient and elegant programming techniques. You can use them to replace Switch-Statements or to Implement Callbacks.
- A Function Pointer always points to function with a specific signature , so all function this pointer will point to must have the same parameters and return type.
The syntax of C++ Function Pointer:
- There are two different types of Function Pointers :
- Pointers to static C++ member functions.
- Pointers to non-static C++ member functions.
- The basic diﬀerence is that all pointers to non-static member functions need a hidden argument (“this.”pointer to an instance of the class).
Define a Function Pointer:
- Function Pointer is nothing else than variable ,so it must be defined as usual.
Initializing Function Pointer:
- To initialize function pointer ,you must give it the address of the function in your program
Using Function Pointer:
- To call the function pointed to by a function pointer, you treat the function pointer as though it was the name of the function you wish to call. The act of calling it performs dereferencing operation, there’s no need to do it yourself:
Generic Sorting Routine:
- If you were to write a sort routine, you might want to allow the function’s caller to choose the order in which the data is sorted; some might need to sort the data in ascending order, others might prefer descending order . The much nicer way of allowing the user to choose how to sort the data is simply to let the user pass in a function to the sort function. This function might take two pieces of data and perform a comparison on them.
Benefits of Function Pointers:
- Function pointers provide a way of passing around instructions for how to do something.
- You can write flexible functions and libraries that allow the programmer to choose behavior by passing function pointers as arguments.
- This flexibility can also be achieved by using classes with virtual functions.