Function Pointers & std::function in C++
Sometimes the function itself is data: callbacks, comparators, and event handlers selected at run time. Raw function pointers (int (*op)(int,int)) do the job with zero overhead but an awkward syntax and no state. std::function<int(int,int)> from <functional> wraps anything callable β free functions, lambdas (even capturing ones), functors, bound members β behind one uniform type.
The flexibility costs a little indirection and possible heap allocation versus a direct call or template parameter. Rule of thumb: templates for compile-time customization, std::function for run-time substitution (callbacks stored in objects, plugin hooks).
Raw pointer syntax
int (*op)(int, int) = add; then op(2, 3) calls through β fast, stateless, and famously hard to read.
std::function erases type
std::function<int(int,int)> f; holds a function, a lambda, or a functor interchangeably β one member type for any behavior.
Stateful callables fit
Unlike raw pointers, std::function stores capturing lambdas β callbacks that remember context just work.
Check before calling
An empty std::function throws std::bad_function_call β test if (f) before invoking anything optional.
#include <iostream>#include <functional>Β int add(int a, int b) { return a + b; }Β int main() { std::function<int(int, int)> op = add; std::cout << op(2, 3) << std::endl; op = [](int a, int b) { return a * b; }; std::cout << op(2, 3) << std::endl; return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.