C++ Function Pointer Tutorial
A function pointer in C++ is a variable that stores the address of a function. Function pointers allow you to call functions dynamically, pass functions as arguments, and implement callback mechanisms.
1. Basic Function Pointer Example
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int (*funcPtr)(int, int) = add;
cout << funcPtr(3, 4) << endl; // Output: 7
return 0;
}
2. Why Use Function Pointers?
- Callbacks: Pass functions as arguments to other functions.
- Dynamic Function Calls: Choose which function to call at runtime.
- Implementing Tables of Functions: Useful in menu-driven programs or interpreters.
3. Passing Function Pointers to Functions
#include <iostream>
using namespace std;
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
void compute(int x, int y, int (*op)(int, int)) {
cout << op(x, y) << endl;
}
int main() {
compute(2, 3, add); // Output: 5
compute(2, 3, multiply); // Output: 6
return 0;
}
4. Array of Function Pointers
#include <iostream>
using namespace std;
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int main() {
int (*ops[2])(int, int) = {add, sub};
cout << ops[0](5, 2) << endl; // Output: 7
cout << ops[1](5, 2) << endl; // Output: 3
return 0;
}
5. Function Pointer Syntax
- Declaration:
return_type (*pointer_name)(parameter_types) - Example:
int (*funcPtr)(int, int);
6. Function Pointers vs Functors vs Lambdas
- Function Pointer: Points to a free/static function.
- Functor: Object with
operator(); can hold state. - Lambda: Anonymous function object; can capture variables.
Summary
- Function pointers store addresses of functions.
- Useful for callbacks and dynamic function calls.
- Syntax can be tricky but powerful for flexible code.
- For more complex scenarios, consider functors or lambdas.