Learn C++
#include "functions/std_function.hpp"

Function Pointers & std::function in C++

//concept

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).

//how it works
1

Raw pointer syntax

int (*op)(int, int) = add; then op(2, 3) calls through β€” fast, stateless, and famously hard to read.

2

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.

3

Stateful callables fit

Unlike raw pointers, std::function stores capturing lambdas β€” callbacks that remember context just work.

4

Check before calling

An empty std::function throws std::bad_function_call β€” test if (f) before invoking anything optional.

//example
#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;
}
Output
5
6
1op first wraps the plain add function and calls through it: 2 + 3 = 5.
2Reassigning a multiplying lambda swaps the behavior at run time with no type change.
36 prints second β€” same variable, new behavior, decided while running.
//use cases
Event and callback systems storing user-supplied handlers
Strategy patterns swapping algorithms (sort orders, cost functions) at run time
Binding member functions with std::bind or lambdas for UI slots
Preferring template parameters when the callable is fixed at compile time

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself β€” building beats watching.