Skip to content

Lambdas and Function Objects

Beginning of the lesson

Lambdas and Function Objects

Treating behaviour as data: callables you can pass, store, and compose

Big idea: In modern C++ a piece of behaviour is just another value. A lambda lets you write a small, unnamed function right where you need it; a function object (functor) is an object whose class defines operator(); and std::function is a uniform box that can hold any of them. Together they let you pass logic into algorithms, register callbacks, and build reusable strategies.
By the end you will be able to:
  • read and write the full lambda syntax [captures](params) -> ret { body },
  • capture variables by value, by reference, and with init-capture,
  • write a functor and explain how a lambda compiles down to one,
  • store any callable in std::function and know what that costs.

1. What is a lambda, and why?

Think of a lambda as a sticky note with an instruction. Instead of writing a full named function somewhere else and referring back to it, you write the instruction on the spot and hand it to whoever needs it. The reader (an algorithm, a thread, a button) can run it later, as many times as it likes.

Before C++11, if you wanted to give std::sort a custom ordering you had to write a separate named function or a functor struct far away from the call site. That scattered the logic and hurt readability. A lambda expression lets you define the function inline:

#include <algorithm>
#include <vector>

std::vector<int> v = {5, 2, 8, 1};
// Sort in DESCENDING order using an inline comparator:
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
// v is now {8, 5, 2, 1}

The [](int a, int b) { return a > b; } part is the whole function, written where it is used. It has no name of its own; the compiler quietly generates one for you.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers