C++C++ Explainer
C++ · 1 · Foundations5 / 36 · 14%

Overloading, Default Args & Lambdas

One name, several signatures — plus inline callable objects.

Examples: overload, default args, [](){}

shortcuts: ← prev · → next · M mark
1

Function Overloading

Same name, different parameter lists. The return type alone is not enough.

Example
example
int  area(int side)          { return side * side; }
int  area(int w, int h)      { return w * h; }
double area(double r)        { return 3.14159 * r * r; }

area(3);       // int version
area(2.0);     // double version
2

Default Arguments

Declared once, in the header — not repeated in the definition.

Example
example
// log.hpp
void log(const std::string& msg, int level = 1);

// log.cpp
void log(const std::string& msg, int level) { /* no default here */ }
WATCH OUT
Default arguments plus overloads easily become ambiguous. Prefer one or the other.
3

Lambdas

An anonymous function object, optionally capturing surrounding state.

Example
example
int factor = 3;
auto scale = [factor](int x) { return x * factor; };   // capture by value
auto bump  = [&factor]()     { factor++; };            // capture by reference

std::sort(v.begin(), v.end(),
          [](const auto& a, const auto& b) { return a.score > b.score; });
4

Capture Pitfalls

A dangling capture outlives the thing it captured.

Common pitfalls
  • ✕[&] capturing a local, then storing the lambda past the scope — dangling reference.
  • ✕Capturing `this` in a lambda stored on a member that outlives the object.
  • ✕[=] silently copies large objects; be explicit about what you capture.