Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 171 ยท Functions

Function Pointers and std::function

Learn C++ function pointers - declaration syntax, callbacks, arrays of functions, std::function, and how they compare with templates and lambdas.

Functions in C++ aren't only things you call. A compiled function lives at an address in memory, and you can store that address in a variable, pass it to another function, keep it in a table and call it later. That is a function pointer, and it's how C++ (and C before it) lets code say "here is what to do, you decide when to do it".

That idea is everywhere: a sort routine that takes your comparison rule, a button that runs your handler when clicked, a menu that maps commands to actions, a library that calls you back when work is done. In this lesson you'll learn the raw function-pointer syntax (and how to tame it with aliases), write callbacks, build dispatch tables, and then meet std::function, the modern wrapper that can hold any callable, including lambdas that capture state. You'll finish with a clear guide to choosing between function pointers, std::function and templates.

A function has an address

Write a function's name without parentheses and you get the function itself, which converts automatically to a pointer to it. The type of that pointer spells out the return type and the parameter types:

C++
int add(int a, int b);

int (*operation)(int, int) = add;   // operation points to add
int (*same)(int, int) = &add;       // & is optional for functions

Read int (*operation)(int, int) from the name outward: operation is a pointer (*operation, in parentheses) to a function taking (int, int) and returning int. The parentheses around *operation matter. Without them, int *operation(int, int) declares a function that returns int*.

Calling through the pointer looks just like a normal call. The older (*operation)(2, 3) form also works and means the same thing.

C++ Storing and calling a function pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A function pointer can only point to functions whose type matches exactly. A function returning long, or taking (int, double), or taking (const int&, const int&) won't fit into int (*)(int, int), and the compiler stops you. A null function pointer is legal to store and compare, but calling it is undefined behavior, so check before you call when null is possible.

Taming the syntax with using

The raw syntax gets ugly fast, especially for a function that takes or returns a function pointer. A type alias (see Type Aliases) gives the type a name, and then everything reads naturally:

C++
using BinaryOp = int (*)(int, int);   // BinaryOp: pointer to int(int, int)

BinaryOp pick(char symbol);           // a function returning a function pointer

// Without the alias, the same declaration is:
int (*pick(char symbol))(int, int);

Both declarations of pick mean the same thing, but only one of them is readable. You can also alias the function type and add the * where you use it: using BinaryFn = int(int, int); then BinaryFn* op = add;. Pick one style per codebase. And when you just need a variable initialized from a function, auto op = add; deduces int (*)(int, int) for you.

Callbacks: passing behavior into a function

The most common use of a function pointer is a callback: a parameter that tells a general-purpose function which specific step to run. The function below applies any int(int) transformation to every element of a vector. It doesn't know or care what the transformation is.

C++ A callback parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::println can print a whole vector in C++23, which keeps the demo short. The output is [1, 4, 9, 16, 25], then [1, 4, 9, 10, 10], then [-1, -4, -9, -10, -10].

The standard library is full of callback parameters. std::sort takes an optional comparison, std::ranges::transform takes a transformation, std::atexit registers a function to run when the program ends, and C's qsort takes a comparison through a plain function pointer. Here is a sort with a custom rule:

C++
bool by_length(const std::string& a, const std::string& b) {
    return a.size() < b.size();
}

std::vector<std::string> words{"banana", "fig", "cherry", "kiwi"};
std::ranges::stable_sort(words, by_length);   // fig, kiwi, banana, cherry

(stable_sort keeps "banana" before "cherry" because they have the same length; plain sort may put equal elements in any order.)

Dispatch tables

Because function pointers are ordinary values, you can put them in arrays and maps. A dispatch table maps a key (a command name, an opcode, a menu choice) to the function that handles it. It replaces a long switch, and adding a command is a one-line change.

C++ A calculator driven by a dispatch table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The input box feeds four lines; the ^ line hits the "unknown operator" branch. Interpreters, state machines and plugin systems are often built around tables like this one.

Pointers to member functions (briefly)

A pointer to a member function is a different kind of type, because a member function needs an object to run on. The syntax uses ClassName::*, and the call needs an object on the left of .* or ->*:

C++
struct Greeter {
    void hello() const { std::println("hello"); }
};

void (Greeter::*method)() const = &Greeter::hello;   // & is required here
Greeter g;
(g.*method)();                                        // prints hello
std::invoke(method, g);                               // the same call, easier to read

You'll rarely write these by hand. A lambda that calls the method, or std::invoke from <functional>, is usually clearer. It's enough to recognize the syntax when you meet it.

std::function: one type for any callable

Plain function pointers have a big limit: they can only point to free functions (and lambdas that capture nothing). They can't carry state. Suppose you want a callback that multiplies by a factor the user chose at run time. A function pointer can't remember that factor.

std::function (header <functional>) solves this. A std::function<int(int)> can hold any callable that can be called with an int and returns something convertible to int: a function, a function pointer, a lambda with captures, or an object with an operator() (a functor). The template argument is the call signature, written like a function type.

C++ std::function holds functions, lambdas and functors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The value goes 1 โ†’ 2 โ†’ 5 โ†’ 50 โ†’ 49. Four completely different kinds of callables live in one vector because they all share the signature int(int). That's what makes std::function the natural type for stored callbacks: event handlers, a list of cleanup steps, a strategy object chosen at run time.

Unlike a null function pointer, an empty std::function is safe to test (it converts to bool) and calling it throws std::bad_function_call instead of crashing. The exact text of what() depends on the standard library; GCC prints bad_function_call.

Lambdas get a full lesson later in Lambda Expressions. For now, read [factor](int x) { return x * factor; } as "an unnamed function that remembers a copy of factor".

Registering event handlers

Here is the classic real-world shape: an object that lets other code subscribe to an event and then calls every subscriber.

C++ An event with std::function subscribers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The second handler captures click_count by reference (&click_count) and updates the caller's variable, which a plain function pointer could never do. That power comes with a responsibility: a stored lambda that captures by reference must not outlive the variable it refers to.

Function pointers vs std::function vs templates

C++ gives you three ways to accept "something callable". They trade flexibility against speed and simplicity:

Function pointer std::function<Sig> Template parameter (auto/typename F)
Holds free functions yes yes yes
Holds capturing lambdas and functors no yes yes
Can be stored in a member or container yes yes only with a known type
Size one pointer (8 bytes on 64-bit) larger (32 bytes with GCC) and may allocate for big captures the callable itself
Call cost indirect call indirect call through type erasure direct call, usually inlined
Works with C APIs yes no no

A template version of apply_to_all looks like this:

C++
void apply_to_all(std::vector<int>& values, auto transform) {   // C++20 abbreviated template
    for (int& value : values) {
        value = transform(value);
    }
}

The compiler generates a separate copy for each callable type, so the call can be inlined and costs nothing extra. That's why standard algorithms like std::sort take their comparisons as template parameters. You'll learn the mechanics in Function Templates.

C++ Comparing the sizes of the three approaches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last two lines show a handy rule: a lambda without captures converts implicitly to a matching function pointer, so you can pass one to a C API like qsort or std::atexit. A lambda that captures anything cannot convert, because a plain pointer has nowhere to keep the captured data.

Choosing in practice:

  • Template / auto parameter for callbacks that a function uses right away and doesn't store, especially in performance-sensitive code. This is the default for generic algorithms.
  • std::function when you need to store callables of different types in one place (members, containers, event systems) or keep a non-template interface in a header.
  • Function pointer for C interoperability, for tables of plain functions, or when you need the smallest and simplest representation. C++26 adds std::function_ref, a lightweight non-owning alternative for parameters; it isn't in C++23.

std::function requires the stored callable to be copyable. If you need to store a lambda that owns a move-only object such as a std::unique_ptr, C++23 adds std::move_only_function in <functional>, which works the same way but only needs the callable to be movable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does int *f(double); declare?

    Without parentheses around *f, the * belongs to the return type. A pointer to a function would be written int (*f)(double).
  2. 2. Which of these can be assigned to a variable of type int (*)(int)?

    Only lambdas without captures convert to plain function pointers. A capturing lambda and a functor carry state, and a function returning long has a different type.
  3. 3. What happens when you call a default-constructed std::function<void()>?

    An empty std::function throws std::bad_function_call when called. You can check for emptiness first because it converts to bool.
  4. 4. You are writing a generic algorithm that calls a user-supplied comparison many times and never stores it. What is usually the best parameter type?

    A template parameter keeps the callable's real type, so the compiler can inline each call and any callable works. That's how std::sort is designed.
  5. 5. Why is std::function a good fit for storing event handlers in a vector?

    Type erasure lets very different callables share one type with the same call signature. It is larger than a pointer, may allocate, and the signature is fixed.

Summary

  • A function pointer stores the address of a function. Its type includes the return and parameter types: int (*op)(int, int) = add;. Parentheses around *op are required.
  • Call through it like a normal function (op(2, 3)). Calling a null function pointer is undefined behavior.
  • Use using Name = Ret (*)(Params); to make function-pointer types readable, or auto.
  • Function pointers enable callbacks and dispatch tables (maps or arrays from keys to handlers).
  • Pointers to member functions use &Class::method and .*/->*; std::invoke and lambdas are friendlier.
  • std::function<Sig> holds any callable with a matching signature, including capturing lambdas and functors. Empty ones throw std::bad_function_call when called.
  • Prefer templates/auto for callbacks used immediately, std::function for stored callbacks, and function pointers for C interop and simple tables.

Next: References, where you'll learn how C++ lets one variable become another name for an existing object.