Small pieces with clear contracts
Every large C++ codebase is built from functions, and the language gives you more ways to write one than most: free functions, member functions, overloads that share a name, templates, lambdas written inline at the point of use. That variety is useful because each form fits a different job. A free function distance(a, b) names a reusable computation. A family of overloads print(int), print(double), print(const Point&) lets callers stop thinking about types. A lambda passed to std::ranges::sort says, right where it matters, what "smaller" means for this sort.
What all of them share is a contract: the parameter types say what goes in and whether the caller's objects can be changed, and the return type says what comes out. In C++ the compiler checks every call against that contract before the program ever runs. This lesson shows how to write contracts that are precise, cheap to call and hard to misuse.
Declarations, definitions and overloads
Definition— declaration and definition
A declaration tells the compiler a function's name, parameter types and return type: double average(const std::vector<double>& xs);. A definition adds the body. A function may be declared many times but defined only once in the whole program (the one-definition rule). The compiler needs to have seen a declaration before a call; the linker needs to find the single definition.
This is why C++ has headers. A library puts its declarations in a header (stats.hpp) and its definitions in a source file (stats.cpp). Every file that calls the functions includes the header, so the compiler can check the calls, and the definitions are compiled once and linked in. Small functions that must be visible everywhere, such as templates and constexpr functions, are defined in the header itself and marked inline (or are implicitly inline), which tells the linker that the identical copies in different files are one function. C++20 modules (import stats;) are the long-term replacement for this textual inclusion; they are supported by current compilers and CMake but are still being adopted, so headers remain what you will see in most code in 2026.
Definition— overloading
Several functions may share a name if their parameter lists differ. At each call the compiler performs overload resolution: it ranks the candidates by how good a match each argument is and picks the best one, or reports an error if two are equally good (an ambiguous call). Return types play no part in choosing.
The ranking, simplified, from best to worst: an exact match (including adding const or binding a reference); a promotion (char, short or bool to int; float to double); a standard conversion (int to double, double to int, any number to bool); a user-defined conversion (a string literal to std::string, through a constructor). A function that is better for one argument and worse for another is ambiguous with its rival.
Definition— default argument
A value used when the caller leaves a trailing argument out: std::string describe(std::string_view s, int times = 1);. Defaults go on the declaration, not repeated on the definition.
Definition— lambda expression
An expression that creates an unnamed function object on the spot: [captures](parameters) { body }. The capture list says which local variables the lambda may use and how: [x] copies x into the lambda when it is created, [&x] refers to the original x, [n = 100] creates a new member initialised to 100, and [=] or [&] capture whatever is used, by copy or by reference.
Functions, overloads and several results
This program declares its functions at the top, uses them in main, and defines them at the bottom, which is how code is split between a header and a source file, compressed into one file.
#include <format>
#include <print>
#include <string>
#include <string_view>
#include <vector>
// Declarations: enough for the compiler to check calls.
double average(const std::vector<double>& xs);
std::string describe(int n);
std::string describe(double x);
std::string describe(std::string_view s, int times = 1);
struct MinMax {
int lo;
int hi;
};
[[nodiscard]] MinMax min_max(const std::vector<int>& v) {
MinMax r{v.front(), v.front()};
for (int x : v) {
if (x < r.lo) r.lo = x;
if (x > r.hi) r.hi = x;
}
return r;
}
int main() {
std::println("{}", describe(3));
std::println("{}", describe(3.0));
std::println("{}", describe("ha", 3));
std::println("{}", describe("ho"));
std::println("{:.2f}", average({2.0, 4.0, 9.0}));
auto [lo, hi] = min_max({31, 4, 15, 9, 26});
std::println("lo={} hi={}", lo, hi);
}
// Definitions can come after main, because main only needed the declarations.
double average(const std::vector<double>& xs) {
double sum = 0;
for (double x : xs) sum += x;
return xs.empty() ? 0.0 : sum / xs.size();
}
std::string describe(int n) { return "int " + std::to_string(n); }
std::string describe(double x) { return std::format("double {:.1f}", x); }
std::string describe(std::string_view s, int times) {
std::string out;
for (int i = 0; i < times; ++i) out += s;
return "text " + out;
}int 3
double 3.0
text hahaha
text ho
5.00
lo=4 hi=31A few details are worth slowing down for.
describe(3)matchesdescribe(int)exactly;describe(3.0)matchesdescribe(double). A string literal cannot convert tointordoubleat all, sodescribe("ho")can only mean thestd::string_viewoverload, reached through a user-defined conversion, withtimestaking its default of 1.average({2.0, 4.0, 9.0})builds a temporary vector from the braces. Binding a temporary to aconst¶meter is allowed and the temporary lives until the end of the full expression, which is exactly long enough.min_maxreturns a small struct and the caller unpacks it with a structured binding,auto [lo, hi] = .... This is the modern answer to "how do I return two values?" Prefer a named struct overstd::pairorstd::tupleonce the meaning of the fields is not obvious;r.loandr.hisay more thanr.firstandr.second.[[nodiscard]]asks the compiler to warn if a caller ignores the result. It costs nothing and catches calls likemin_max(v);that do no work. The standard library marks many of its own functions this way.
Returning a struct by value is not slow. Since C++17, return MinMax{...}; constructs the result directly in the caller's variable (guaranteed copy elision), and returning a named local is almost always optimised the same way. Return values are the clearest way to give back results, and the C++ Core Guidelines recommend them over out-parameters.
A result that may be missing
Some functions cannot always produce an answer: a search may find nothing, a parse may fail. Old C and C++ code returns a "magic" value such as -1 or a null pointer. C++17's std::optional says it in the type: a std::optional<int> holds either an int or nothing.
#include <optional>
#include <print>
#include <string>
#include <vector>
// Recursion: a function that calls itself on a smaller problem.
long long power(long long base, int exp) {
if (exp == 0) return 1;
long long half = power(base, exp / 2);
return exp % 2 == 0 ? half * half : half * half * base;
}
// std::optional: a result that may be absent, without a magic value like -1.
std::optional<std::size_t> find_index(const std::vector<std::string>& v, const std::string& target) {
for (std::size_t i = 0; i < v.size(); ++i) {
if (v[i] == target) return i;
}
return std::nullopt;
}
int main() {
std::println("{} {}", power(2, 10), power(3, 13));
std::vector<std::string> planets{"Mercury", "Venus", "Earth", "Mars"};
if (auto i = find_index(planets, "Earth")) {
std::println("Earth at index {}", *i);
}
auto pluto = find_index(planets, "Pluto");
std::println("Pluto found? {}", pluto.has_value());
std::println("index or -1: {}", pluto ? static_cast<long>(*pluto) : -1L);
// An immediately invoked lambda initialises a const with a little logic.
const int days = [](int month) {
switch (month) {
case 2: return 28;
case 4: case 6: case 9: case 11: return 30;
default: return 31;
}
}(9);
std::println("September has {} days", days);
}1024 1594323
Earth at index 2
Pluto found? false
index or -1: -1
September has 30 daysif (auto i = find_index(...)) declares i and tests it in one step: an optional converts to true when it holds a value, and *i reads the value. Calling * on an empty optional is undefined behaviour; .value() throws an exception instead, and .value_or(default) supplies a fallback. When "nothing" needs an explanation (why did the parse fail?), use std::expected, which you will meet in the Professional level.
power is recursive: it computes base to the power exp by squaring the result for half the exponent, so it needs about log₂(exp) calls instead of exp multiplications. The last line shows a useful idiom: a lambda defined and called on the spot to initialise a const variable that needs a few lines of logic.
Lambdas at work
Lambdas are everywhere in modern C++, mostly as arguments to algorithms. This program ranks five runners in an imaginary club race and shows each kind of capture.
#include <algorithm>
#include <functional>
#include <print>
#include <string>
#include <vector>
struct Runner {
std::string name;
int seconds;
};
int main() {
std::vector<Runner> race{
{"Achieng", 7810}, {"Kiprono", 7795}, {"Selam", 7799}, {"Tadesse", 7841}, {"Amane", 7802}};
// A lambda as a comparison: sort by time.
std::ranges::sort(race, [](const Runner& a, const Runner& b) { return a.seconds < b.seconds; });
std::println("winner: {}", race.front().name);
// Capture by value: the lambda keeps its own copy of limit.
int limit = 7805;
auto under = [limit](const Runner& r) { return r.seconds < limit; };
limit = 0; // does not affect the copy inside the lambda
std::println("under 7805 s: {}", std::ranges::count_if(race, under));
// Capture by reference: the lambda updates total in the enclosing scope.
int total = 0;
std::ranges::for_each(race, [&total](const Runner& r) { total += r.seconds; });
std::println("mean: {} s", total / static_cast<int>(race.size()));
// A generic lambda: auto parameters make it work for any type with +.
auto twice = [](auto x) { return x + x; };
std::println("{} {} {}", twice(21), twice(1.25), twice(std::string("ab")));
// mutable lets a by-value capture change between calls.
auto next_id = [n = 100]() mutable { return n++; };
int first = next_id();
int second = next_id();
std::println("ids {} {}", first, second);
// std::function stores any callable with a given signature.
std::vector<std::function<int(int)>> steps{
[](int x) { return x + 3; }, [](int x) { return x * 2; }, twice};
int value = 1;
for (const auto& step : steps) value = step(value);
std::println("value: {}", value);
}winner: Kiprono
under 7805 s: 3
mean: 7809 s
42 2.5 abab
ids 100 101
value: 16Read the captures carefully, because they decide what the lambda sees.
undercapturedlimitby value when it was created. Settinglimit = 0afterwards does not change the lambda's copy, so it still counts the three times under 7805.- The lambda passed to
for_eachcapturedtotalby reference, so it added to the variable inmain. twicehas anautoparameter, which makes it a generic lambda: the compiler generates a version for each argument type used. Adding astd::stringto itself concatenates.next_iduses an init capture,n = 100, and ismutable, which allows the call operator to change its own copy ofn. Each call returns the next number.std::function<int(int)>can hold any callable that takes and returns anint: a lambda, a function, eventwice. That flexibility costs something (it may allocate memory and calls go through an indirection), so use it when you need to store different callables in one place, as in this vector of steps, and plainautoor a template parameter otherwise.
Under the hood a lambda is a small class the compiler writes for you: its captures become data members and its body becomes operator(). That is why lambdas are as fast as hand-written functions, and why passing one to std::ranges::sort lets the compiler inline the comparison into the sorting loop.
Example— A reference capture that outlives its variable
Capturing by reference is safe only while the captured variable is alive. This function returns a lambda that refers to a local which is about to be destroyed:
auto make_counter() {
int count = 0;
return [&count] { return ++count; }; // count dies when make_counter returns
}Calling the returned lambda is undefined behaviour. The fix is to capture by value with mutable ([count = 0]() mutable { return ++count; }), so the lambda owns its counter. A good rule: capture by reference only for lambdas used immediately, such as those passed straight to an algorithm; capture by value for lambdas that are stored, returned or handed to another thread.
Common misconceptions
Misconception
"Function arguments are evaluated from left to right." C++ does not specify the order in which a function's arguments are evaluated. This line calls the counter from the previous section three times in one statement:
std::println("{} {} {}", next_id(), next_id(), next_id());Compiled with GCC 14 on x86-64 it printed 102 101 100: GCC happened to evaluate the arguments from right to left. Another compiler, or another optimisation level, may differ. When the order of side effects matters, put them in separate statements.
Misconception
"Overloading on the return type lets me have int parse(s) and double parse(s)." The return type is not part of overload resolution, so those two declarations conflict. Give the functions different names, take the result type as a template argument (parse<double>(s)), or return a type that holds either.
Misconception
"Default arguments and overloading do the same thing, so it doesn't matter which I use." They interact. void f(int, int = 0) and void f(int) together make f(1) ambiguous. Use a default argument when the omitted value is truly a default of the same operation; use overloads when the argument types differ.
Misconception
"std::function is how you pass a function in C++." It is one way, and often not the best. To accept a callable in a function you are writing, a template parameter or an auto parameter (as in void each(const auto& f)) lets the compiler inline the call. Keep std::function for when you must store callables of different types, and consider std::move_only_function (C++23) when the callable cannot be copied.
How professionals write functions
Short functions with honest names and parameter types that state the contract are the core of readable C++. Some habits that experienced teams share:
- Make the type say it.
const std::vector<double>& pricestells the reader the function only looks;std::vector<double>& priceswarns that it changes the caller's vector; a return type ofstd::optional<std::string>says the answer may be missing. Comments that repeat what the types already say go out of date; types do not. - Return results, don't fill out-parameters. Use structs with named fields for several results,
std::optionalfor absent ones andstd::expectedfor failures with a reason. - Prefer free functions in a namespace for operations that do not need private access to a class. They are easier to test and extend.
- Hide helpers. A function used only inside one
.cppfile belongs in an unnamed namespace (namespace { ... }), which gives it internal linkage: no other file can call it, and its name cannot clash with a helper of the same name elsewhere in the program. - Keep lambdas short. If a lambda grows past a few lines or is used in two places, give it a name as a function.
- Mark functions that cannot fail cheaply.
constexprwhere the computation could happen at compile time,noexceptwhere a function never throws (you will see why it matters for moves),[[nodiscard]]where ignoring the result is a bug.
Exercises
1. Functions, overloading and lambdas
CoreComputationalWhat does this program print? (Each call prints a word and a space.)
#include <print>
#include <string>
void f(int) { std::print("int "); }
void f(double) { std::print("double "); }
void f(const std::string&) { std::print("string "); }
int main() {
f('x');
f(2.5f);
f(true);
f("hi");
std::println("");
}
2. Functions, overloading and lambdas
StretchComputationalA colleague adds an overload, and now the program behaves differently:
void show(bool b) { std::println("bool {}", b); }
void show(const std::string& s) { std::println("string {}", s); }
int main() { show("hello"); }
What does it print, and why?
3. Functions, overloading and lambdas
Warm-upComputationalWhat does this program print?
#include <print>
int main() {
int x = 10;
auto by_value = [x] { return x + 1; };
auto by_reference = [&x] { return x + 1; };
x = 20;
std::println("{} {}", by_value(), by_reference());
}
4. Functions, overloading and lambdas
Warm-upComputationalWhat does this program print?
#include <print>
int volume(int l, int w = 2, int h = 3) { return l * w * h; }
int main() {
std::println("{} {} {}", volume(1), volume(1, 5), volume(2, 2, 2));
}
5. Functions, overloading and lambdas
CoreComputationalThe lesson's power function, with a counter added, is called as power(2, 10). How many times does power run in total, counting the first call?
int calls = 0;
long long power(long long base, int exp) {
++calls;
if (exp == 0) return 1;
long long half = power(base, exp / 2);
return exp % 2 == 0 ? half * half : half * half * base;
}
6. Functions, overloading and lambdas
CoreHumannext_id is a lambda that returns 100, 101, 102, ... on successive calls. What can you say about the output of
std::println("{} {} {}", next_id(), next_id(), next_id());
7. Functions, overloading and lambdas
CoreHumanA class Contact has a member std::string name_;. Which signature for set_name follows the guidelines in this course for a function that keeps its own copy of the argument?
Further reading and resources
- Function declaration · cppreference.com
- Overload resolution · cppreference.comThe full rules; the lesson gives the version you need day to day.
- Lambda expressions · cppreference.com
- std::optional · cppreference.com
- C++ Core Guidelines: F (functions)The section on functions covers parameter passing, return values and lambdas, each rule with a reason.