Vividly / Languages / C++

C++

C++ is C with added support for objects, templates, and richer function features, and it is for programmers who want high performance without giving up useful abstractions.

Read the lesson →

Why this matters

C++ keeps the speed and close-to-the-metal control of C, then adds features that make large programs far more manageable. Classes let you bundle data with the functions that operate on it. References give you cleaner parameter passing than raw pointers. Templates let you write one function that works for many types. You get to choose how much abstraction to use, which is the defining characteristic of the language.

It is everywhere that performance matters. Game engines, web browsers, databases, financial trading systems, and scientific simulations all lean heavily on C++. When you understand how its functions work, the standard library stops being mysterious, because containers and algorithms are built from the very same tools of overloads, references, templates, and lambdas that you will learn here.

Learning C++ also makes you think carefully about resource ownership. Because there is no garbage collector, the language pushes you toward patterns that make ownership explicit, and modern C++ gives you powerful tools to express it. Even if you later work in a language with automatic memory management, the habits of clear ownership and careful function boundaries will serve you well.

The big picture

C++ still compiles straight to native machine code. There is no virtual machine and no heavyweight runtime interpreting your program. What has changed is the type system: it is much richer, and it lets you describe intent with far greater precision. A function parameter can say that a value is an integer, and that it is a read-only reference to one, or that it may be moved from.

Functions in C++ come in several flavors. Free functions look much like C functions. Member functions live inside a class and receive a hidden this pointer. Constructors initialize objects, operators overload familiar symbols, and virtual functions enable runtime polymorphism. Overloading lets several functions share a name as long as their parameter lists differ.

A central idea is the value category of an expression. An lvalue names an object that persists, while an rvalue is a temporary you can safely consume. Understanding that distinction opens the door to move semantics, which let a function take ownership of a temporary's resources instead of copying them. Once you see it, many confusing C++ idioms suddenly make sense.

Core ideas

Free vs member functions

You can write functions outside any class, just as you would in C, or inside a class as member functions. A member function receives a hidden this pointer that refers to the particular object it was called on, which is how it accesses that object's data. You can mark a member function const to promise it will not modify the object.

Choosing between a free function and a member function is a design decision. If an operation naturally belongs to an object and needs access to its private data, make it a member. If it can be expressed entirely in terms of the public interface, a free function is often cleaner and keeps the class small.

Free vs member functionsexample
class Counter {
    int value = 0;
public:
    void increment() { ++value; }
    int get() const { return value; }
};

Watch out. Forgetting const on a member function that only reads data. Without it, you cannot call that function through a const object or a const reference, which is a common and frustrating compile error.

Passing by value

When you pass an argument by value, C++ makes a copy for the parameter, just as C does. For an int that copy is trivial. For a class type, copying means running its copy constructor, which might duplicate a large buffer and cost real time. The function then works only with the copy, so the caller's original object is untouched.

Pass by value is a good default for small, cheap-to-copy types such as integers, enums, and small structs. It gives the function its own private value with no aliasing surprises, and modern compilers are very good at optimizing away unnecessary copies. For larger objects you will usually want a reference instead.

Passing by valueexample
void scale(int n, int factor) {
    n = n * factor;
}

Watch out. Assuming a by-value parameter can change the caller's variable. It cannot. If you need to modify the original, take a reference with the ampersand operator.

Passing by reference

A reference is an alias for an existing object. When a parameter is a reference, no copy is made: the parameter simply refers to the argument the caller supplied. Changes to the parameter therefore change the original object. A reference must always refer to something valid and cannot be resealed to point elsewhere, which makes it safer than a raw pointer.

References are ideal when a function needs to modify an argument, or when copying the object would be expensive. The syntax uses an ampersand in the parameter declaration, but at the call site you pass the variable normally, with no special operator. That clean call syntax is one of the reasons references are preferred over pointers for ordinary parameter passing.

Passing by referenceexample
void increment(int &n) {
    ++n;
}
int main() {
    int x = 3;
    increment(x);
}

Watch out. Trying to bind a non-const reference to a temporary, as in increment(5). A literal is not a modifiable object. Use a const reference if the function only reads the value.

const references

A const reference gives you the best of both worlds for read-only arguments. You avoid copying the object, yet the function is forbidden from changing it. Because a const reference cannot modify its target, it is allowed to bind to temporary values and literals, which makes calls wonderfully flexible. This is the most common parameter type for strings and containers.

Consider a function that prints a name. Taking the string by value would copy it; taking a non-const reference would prevent calling the function with a string literal; taking a const reference does neither. The compiler enforces the promise, so an accidental write through that reference simply will not compile.

const referencesexample
#include <string>
#include <iostream>
void print(const std::string &name) {
    std::cout << name << "\n";
}

Watch out. Returning a const reference to a local object. The local is destroyed on return and the reference dangles. Return by value for locally created results.

Return values and moves

A function returns a value by writing return followed by an expression whose type matches the declared return type. Returning by value is the default and is usually what you want. Compilers routinely eliminate the copy through return value optimization, and where a copy is still needed they can often perform a move instead, transferring the object's resources cheaply.

Move semantics let an object give up its internal buffer to another object rather than duplicating it. You signal this with an rvalue reference, written with two ampersands, and the standard library function std::move casts a value into that category. This is why returning a large vector from a function is efficient in modern C++.

Return values and movesexample
#include <vector>
std::vector<int> make_data() {
    std::vector<int> v{1, 2, 3};
    return v;
}

Watch out. Returning a reference or pointer to a local variable. Use return by value and let the compiler move or elide the result, instead of trying to return an address that will dangle.

Overloads and defaults

C++ lets several functions share the same name as long as their parameter lists differ. This is called overloading, and the compiler picks the right version at compile time by matching the arguments you pass. Overloads let you present one natural name for an operation that makes sense on several types, such as printing an integer or a string.

A default argument lets a caller omit trailing parameters, and the compiler fills in the value you specified in the declaration. Defaults are handy for optional configuration, but keep them in the declaration rather than repeating them in the definition. Be careful not to create overloads that become ambiguous once defaults are applied.

Overloads and defaultsexample
int power(int base, int exp = 2) {
    int result = 1;
    while (exp-- > 0) result *= base;
    return result;
}

Watch out. Defining two overloads that a call cannot distinguish, such as f(int) and f(int, int = 0). Calling f(1) matches both, so the compiler reports an ambiguous call.

inline functions

Marking a function inline asks the compiler to consider expanding its body directly at each call site, avoiding the overhead of a function call. It is only a hint: the compiler may ignore it, especially for large or recursive functions. In practice the bigger effect of inline is that it permits the definition to live in a header without violating the one definition rule.

Small functions in headers are the typical use. Without inline, including the same function definition in multiple source files would produce duplicate definitions at link time. With inline, the linker is told that all those definitions are the same and may be merged.

inline functionsexample
inline int square(int x) {
    return x * x;
}

Watch out. Expecting inline to guarantee a performance win. The compiler decides whether to actually inline based on its own heuristics, so treat it mainly as a linkage and header-file tool.

Lambdas

A lambda is an unnamed function object you can write right where you need it. It has a parameter list, an optional return type, and a body, plus a capture list that says which surrounding variables it may use. Lambdas are everywhere in modern C++, especially as arguments to standard algorithms such as sort and for_each.

Captures can be by value or by reference. Capture by value copies the variable into the closure at creation time; capture by reference lets the lambda see later changes. You will often see a short capture list like [&] for everything by reference or [=] for everything by value, though naming each capture explicitly is clearer in larger functions.

Lambdasexample
#include <algorithm>
#include <vector>
int main() {
    std::vector<int> v{3, 1, 2};
    std::sort(v.begin(), v.end(),
              [](int a, int b) { return a < b; });
}

Watch out. Capturing a local variable by reference and using the lambda after that variable has gone out of scope. The captured reference then dangles, so capture by value when the closure must outlive the local.

Virtual functions

A virtual function is a member function whose behavior can be replaced by a derived class. When you call it through a pointer or reference to the base class, C++ decides at runtime which version to run based on the actual object type. This is runtime polymorphism, and it is implemented with a hidden table of function pointers called a virtual table.

Mark a function with the virtual keyword in the base class and use override in the derived class to make your intent explicit and catch mistakes. A base class meant to be deleted through a pointer should also have a virtual destructor, so that destroying a derived object runs the correct cleanup code.

Virtual functionsexample
struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
};
struct Square : Shape {
    double side;
    double area() const override { return side * side; }
};

Watch out. Deleting a derived object through a base pointer when the base destructor is not virtual. That skips the derived destructor and leaks resources, so make the base destructor virtual.

Functions

Functions are the working units of C++ just as they are of C, but the language gives you far more ways to shape them. You can overload a name, give parameters default values, take arguments by value or by reference, return objects efficiently through moves, and pass tiny anonymous functions as lambdas. Mastering these options is what makes C++ code both expressive and fast.

The section below walks through each decision you face when writing a function. You will see how the compiler resolves an overloaded call, why a const reference is often the best parameter choice, and how move semantics fit into returning values. Understanding the reasoning behind each choice matters more than memorizing the syntax.

Value, reference, and const reference

Choosing a parameter type is really a question about copies and modification. By value gives the function a private copy, which is ideal for cheap types. By reference avoids the copy and allows modification. By const reference avoids the copy while forbidding modification, and it can bind to temporaries.

A good rule of thumb is to pass small scalars by value, pass large read-only objects by const reference, and pass by non-const reference only when the function genuinely needs to change the argument. This keeps calls efficient and makes the function's effect on its arguments obvious.

Value, reference, and const referenceexample
void report(const std::string &s);
void normalize(std::string &s);
void set_flag(bool enabled);

Returns and copy elision

Returning by value is the normal choice. The compiler is allowed to construct the return object directly in the caller's storage, a trick called copy elision, so there may be no copy at all. When a copy cannot be avoided, a move is often used instead, which transfers ownership of internal buffers rather than duplicating them.

This is why returning a vector, string, or other container by value is perfectly reasonable in modern C++. Resist the old habit of returning a pointer or reference just to dodge a copy, because that usually creates lifetime bugs and makes the interface harder to use.

Returns and copy elisionexample
#include <string>
std::string build() {
    std::string s = "hello";
    s += " world";
    return s;
}

Overload resolution

When several functions share a name, the compiler builds a set of candidates and ranks them by how well the arguments match. An exact match beats a conversion, and fewer conversions beat more. This all happens at compile time, so an overloaded call has no runtime cost compared with calling a uniquely named function.

Ambiguity arises when two candidates are equally good. Defaults and implicit conversions are frequent culprits. When the compiler complains that a call is ambiguous, the fix is usually to add a more specific overload or to make a constructor explicit so unwanted conversions cannot sneak in.

Overload resolutionexample
void draw(int x);
void draw(double x);
void draw(const char *s);
// draw(3) picks the int overload exactly.

Default arguments

A default argument supplies a value when the caller leaves a parameter out. Defaults are written in the declaration and are substituted by the compiler at the call site, so they are a compile-time convenience rather than a runtime feature. They are useful for optional flags, sizes, and policies.

Write the default only once, in the declaration visible to callers, and do not repeat it in the definition. Be cautious about defaults that interact with overloads, because a call that omits an argument might then match more than one function.

Default argumentsexample
void log(const std::string &msg,
         int level = 1);
// log("start") uses level 1.

Lambdas and captures

A lambda expression creates a closure: a small object that behaves like a function and can carry state captured from its surroundings. The square brackets introduce the capture list, followed by the parameter list and body. A lambda with no captures can even convert to a plain function pointer.

Capture by value copies what you name, freezing it at the moment the lambda is created. Capture by reference keeps a link to the original variable, which sees later changes but becomes dangerous if the variable dies first. Naming captures explicitly makes these lifetimes easier to reason about.

Lambdas and capturesexample
int offset = 10;
auto add_offset = [offset](int x) {
    return x + offset;
};

Function objects

A function object, or functor, is simply a class with a call operator defined. Because it is a real object, it can hold state and be customized with constructor arguments. The standard library treats function objects and lambdas interchangeably, since a lambda is really just compiler-generated functor syntax.

Functors can outperform plain function pointers because the compiler sees the exact function being called and can inline it. That is why algorithms accept them as template parameters rather than forcing a function pointer, which would hide the call behind an indirect jump.

Function objectsexample
struct Multiply {
    int factor;
    int operator()(int x) const {
        return x * factor;
    }
};

Virtual dispatch

Calling a virtual function through a base pointer or reference triggers dynamic dispatch: the program looks up the correct override in the object's virtual table at runtime. The cost is usually one indirect call, which is negligible for most application code and buys you the ability to treat many related types uniformly.

Virtual functions only do their job when you call through a pointer or reference. Calling one on a plain base object uses the base version, a behavior called slicing when a derived object is copied into a base variable. Use references or pointers to polymorphic base classes.

Virtual dispatchexample
Shape *s = new Square{};
double a = s->area();
delete s;

Move semantics in calls

An rvalue reference parameter, written with two ampersands, can bind only to temporaries or to values the caller explicitly moves. Inside the function you can steal that object's resources, leaving it in a valid but empty state. This is how functions consume large arguments without copying their contents.

Use std::move when you want to hand ownership of an existing object to such a parameter. After moving from a variable you should not rely on its value, though it remains valid for destruction or reassignment. Move semantics are most valuable for types that manage heap memory, such as strings and vectors.

Move semantics in callsexample
#include <utility>
void consume(std::string &&s) {
    stored = std::move(s);
}
consume(std::string("temp"));

Function reference

These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.

function definition

User-defined form

A function definition supplies the name, typed parameters, return type, and body that run when the function is called. It is one of the basic building blocks of a C++ program.

Syntaxint add(int a, int b) { return a + b; }
Parametersa — First integer parameter
b — Second integer parameter
ReturnsThe expression after return; here an int. A void function returns no value.
function definitionexample
int add(int a, int b) {
    return a + b;
}

What you can do with it. Group a repeated operation into one named block Break a program into testable units Expose clear behavior while hiding its details

Choose it when. Choose a definition when you are implementing behavior, rather than a declaration in a header that only states the interface.

MistakeFix
Forgetting a return on some code pathEvery path in a non-void function must return a value of the right type.
Declaring the function but never defining itProvide exactly one definition, usually in a .cpp file, or linking fails.

reference parameter

User-defined form

A reference parameter is an alias for the caller's object, so changes inside the function affect the original. Unlike a pointer, a reference cannot be null once bound.

Syntaxvoid increment(int &n) { ++n; }
Parametersn — Reference (alias) to the caller's int
ReturnsNothing; changes flow to the original object through the alias.
reference parameterexample
void increment(int &n) {
    ++n;
}

int main() {
    int x = 5;
    increment(x);
}

What you can do with it. Modify a caller's variable Avoid copying a medium-sized object Return several results through out-parameters

Choose it when. Choose a reference when the function must change its argument and that argument must exist, rather than a nullable pointer.

MistakeFix
Assuming a reference makes a copyIt is an alias; mutating n changes the original x.
Using a reference when null is a valid stateUse a pointer instead, because a reference must always bind to a real object.

const reference parameter

User-defined form

A const reference passes an object by alias while forbidding changes through that alias. You get the speed of no copying plus a read-only guarantee.

Syntaxvoid print(const std::string &s) { std::cout << s << '\n'; }
Parameterss — Read-only reference to a std::string
ReturnsNothing.
const reference parameterexample
#include <string>
#include <iostream>

void print(const std::string &s) {
    std::cout << s << '\n';
}

What you can do with it. Pass large strings and vectors without copying Write read-only APIs that promise no mutation Accept temporaries safely as arguments

Choose it when. Choose a const reference for large read-only inputs, rather than by-value passing that duplicates the whole object.

MistakeFix
Using const reference for tiny scalars like intJust pass small types by value; the indirection saves nothing.
Returning a const reference to a local objectReturn by value, because the local dies when the function exits.

function overloading

User-defined form

Overloading lets several functions share one name as long as their parameter lists differ. The compiler picks the matching version from the arguments at each call.

Syntaxint add(int a, int b); double add(double a, double b);
Parametersparameters — The differing types that distinguish each overload
ReturnsWhatever the selected overload's signature declares.
function overloadingexample
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }

What you can do with it. Use one intuitive name across several types Offer convenience versions with fewer arguments Keep APIs readable without type in the name

Choose it when. Choose overloading when operations are conceptually the same across types, rather than inventing a different name for each.

MistakeFix
Trying to overload only by return typeC++ cannot distinguish overloads by return type; vary the parameters instead.
Creating an ambiguous call with convertible argumentsAdd an exact-match overload or clarify with a cast at the call site.

lambda

Expression / user-defined form

A lambda is an unnamed function you write inline, with the option to capture variables from its surroundings. It is ideal for short callbacks close to where they are used.

Syntax[](int x) { return x * 2; }
Parametersx — The lambda's integer argument
ReturnsWhatever the body returns, inferred by the compiler.
lambdaexample
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> v{3, 1, 2};
    std::sort(v.begin(), v.end(),
              [](int a, int b) { return a > b; });
}

What you can do with it. Supply a custom comparator to an algorithm Write a short event callback Capture local state for a one-off helper

Choose it when. Choose a lambda for a short, local function used once, rather than a named function that adds distance from its use.

MistakeFix
Capturing by reference and using the lambda after locals dieCapture by value with [=] or [x] if the lambda must outlive the scope.
Modifying a value captured by copyMark the lambda mutable, or capture by reference if the lifetime is safe.

std::sort

Standard library function

std::sort rearranges the elements of a range into order, in place. It uses operator< by default but accepts a custom comparator for any ordering you need.

Syntaxstd::sort(vec.begin(), vec.end());
Parametersfirst — Iterator to the first element
last — Iterator one past the last element
comp — Optional comparator returning true if a comes before b
ReturnsNothing; the range is reordered in place.
std::sortexample
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> v{3, 1, 2};
    std::sort(v.begin(), v.end());
}

What you can do with it. Sort a vector of numbers or records Apply a custom order such as descending Prepare data before a binary search

Choose it when. Choose std::sort for random-access containers like vector and array, rather than the member sort of std::list.

MistakeFix
Passing a comparator with <= instead of <The comparator must be a strict weak ordering, so equal elements compare false both ways.
Holding iterators or references across the sortSorting moves elements, so old positions and references are no longer reliable.

std::vector::push_back

Method

push_back appends an element to the end of a vector, growing its storage automatically when capacity runs out. It is the normal way to build a vector over time.

Syntaxvoid push_back(const T &value);
Parametersvalue — The element to append
ReturnsNothing; the vector is modified in place.
std::vector::push_backexample
#include <vector>

int main() {
    std::vector<int> v;
    v.reserve(3);
    v.push_back(10);
    v.push_back(20);
}

What you can do with it. Accumulate results in a growing list Read an unknown number of items into a container Build a dynamic array of objects

Choose it when. Choose push_back to add an existing object to a vector, rather than emplace_back when you can construct it in place.

MistakeFix
Holding a reference or iterator across a push_backReallocation invalidates them; call reserve first or reacquire after the call.
Using push_back to build an object in placeUse emplace_back when you want to construct the element directly from arguments.

std::string::size

Method

size returns how many characters are currently stored in a string. It reflects the content length, not how much memory the string has reserved.

Syntaxsize_t size() const;
ReturnsThe current number of characters as a size_t.
std::string::sizeexample
#include <string>

std::size_t length(const std::string &s) {
    return s.size();
}

What you can do with it. Set bounds for a loop over characters Check whether a string is empty Compute buffer sizes for output

Choose it when. Choose size when you need the actual length of a string, rather than capacity when you care about reserved memory.

MistakeFix
Comparing a signed int with size()size() is unsigned; use size_t or std::ssize for the loop index.
Confusing size() with capacity()size() is content length, while capacity() is allocated storage.

std::make_unique

Standard library function

make_unique constructs an object on the heap and wraps it in a std::unique_ptr, an owner that deletes the object automatically when the pointer goes out of scope.

Syntaxauto p = std::make_unique<int>(42);
Parametersargs — Arguments forwarded to the object's constructor
ReturnsA std::unique_ptr<T> that exclusively owns the new object.
std::make_uniqueexample
#include <memory>

int main() {
    auto p = std::make_unique<int>(42);
}

What you can do with it. Allocate heap objects without manual delete Enforce exclusive ownership in APIs Make exception-safe dynamic allocation

Choose it when. Choose make_unique whenever you need heap allocation with automatic cleanup, rather than managing raw new and delete yourself.

MistakeFix
Using raw new and delete insteadPrefer make_unique so cleanup happens automatically even if an exception is thrown.
Trying to copy a unique_ptrMove it with std::move, or use shared_ptr when sharing is genuinely needed.

std::move

Standard library function

std::move casts a value to an rvalue reference, allowing a move constructor to steal its resources instead of copying them. It does not move anything by itself.

Syntaxauto b = std::move(a);
Parameterst — The object you are willing to have moved from
ReturnsAn rvalue reference to t.
std::moveexample
#include <string>
#include <utility>

int main() {
    std::string a = "hello";
    std::string b = std::move(a);
}

What you can do with it. Transfer ownership of strings and vectors cheaply Avoid deep copies when handing off large data Implement move constructors and move assignment

Choose it when. Choose std::move when you are done with an object and want to transfer its resources, rather than copy it.

MistakeFix
Reading a moved-from object expecting its old valueA moved-from object is valid but in an unspecified state; only reassign or destroy it.
Applying std::move to a const objectconst cannot be moved from, so the compiler falls back to a copy.

std::string::substr

Method

substr returns a new string made from a slice of the original, starting at a position and spanning a number of characters. The result is an independent copy.

Syntaxstd::string substr(size_t pos, size_t count = npos) const;
Parameterspos — Index where the slice begins
count — How many characters to take, defaulting to the end
ReturnsA new std::string containing the selected characters.
std::string::substrexample
#include <string>

std::string ext(const std::string &name) {
    auto dot = name.find('.');
    return name.substr(dot + 1);
}

What you can do with it. Extract a file extension Split a line on a delimiter Parse fixed-width fields from text

Choose it when. Choose substr when you need an owned copy of part of a string, rather than string_view when a borrowed view is enough.

MistakeFix
Passing a pos beyond the string's lengthCheck the index first, because an out-of-range pos throws std::out_of_range.
Forgetting that substr copies the charactersUse std::string_view when you only need a non-owning view of the slice.

std::find

Standard library function

std::find walks a range and returns an iterator to the first element equal to a value. If nothing matches, it returns the end iterator.

Syntaxauto it = std::find(v.begin(), v.end(), value);
Parametersfirst — Start of the range
last — One past the end of the range
value — The value to search for
ReturnsIterator to the first match, or last when there is no match.
std::findexample
#include <algorithm>
#include <vector>

bool has(const std::vector<int> &v, int x) {
    return std::find(v.begin(), v.end(), x) != v.end();
}

What you can do with it. Check whether a container holds a value Locate an element before erasing it Perform a simple linear search

Choose it when. Choose std::find for a straightforward linear search, rather than binary search when the range is already sorted.

MistakeFix
Dereferencing the result without checking itCompare with end() first, because dereferencing end() is undefined behavior.
Using it on large sorted dataOn sorted ranges, std::binary_search or lower_bound is much faster.

std::cout

Standard library object

std::cout is the standard output stream. You write values to it with the << operator, which works for many built-in and user-defined types.

Syntaxstd::cout << "Value: " << x << '\n';
Parametersvalue — The value inserted into the stream
ReturnsThe stream itself, which is why insertions can be chained.
std::coutexample
#include <iostream>

int main() {
    int n = 7;
    std::cout << "n = " << n << '\n';
}

What you can do with it. Print variables with type-safe formatting Write debug and status messages Chain several values into one line

Choose it when. Choose std::cout for type-safe C++ output, rather than printf when you want compile-time checked insertion.

MistakeFix
Mixing std::cout and printf without careThe streams can get out of sync; prefer one style, or call std::ios::sync_with_stdio appropriately.
Using std::endl on every linestd::endl flushes and can be slow; use '\n' unless you truly need a flush.

std::function

Standard library class template

std::function is a type-erased wrapper that can hold any callable matching a signature: a plain function, a lambda, or a function object. It lets you store callbacks in variables and containers.

Syntaxstd::function<int(int)> f = [](int x){ return x + 1; };
Parameterscallable — Any callable whose signature matches the template argument
ReturnsCalling it invokes the stored callable and returns its result.
std::functionexample
#include <functional>

std::function<int(int)> make() {
    int offset = 10;
    return [offset](int x) { return x + offset; };
}

What you can do with it. Store callbacks for later use Implement the strategy pattern Enable recursive lambdas by capturing the wrapper

Choose it when. Choose std::function when you must store or pass callables of differing concrete types, rather than a template parameter when the type is fixed.

MistakeFix
Calling an empty std::functionCheck it converts to bool first, since calling an empty one throws std::bad_function_call.
Storing a lambda that captures a dangling referenceCapture by value when the stored callable outlives the captured locals.

Common mistakes here

MistakeFix
Returning a reference to a local variableReturn by value and let the compiler optimize the copy away with move or elision.
Taking a non-const reference to a temporaryUse a const reference if the function only needs to read the argument.
Creating ambiguous overloads with default argumentsChange the parameter lists so each call matches exactly one function.
Omitting a virtual destructor in a polymorphic base classDeclare the base destructor virtual so derived destructors run on deletion.
Using a captured reference after its variable is destroyedCapture by value when the lambda must outlive the local variable.

The example, line by line

This short program defines a function taking a const reference and calls it from main.

CodeWhat it does
1#include <iostream>Includes the iostream header so standard output is available.
2#include <string>Includes the string header for the std::string type used below.
3void greet(const std::string &name) {Defines greet taking a const reference, so no copy is made and the string cannot change.
4 std::cout << "Hello, " << name << "!\n";Prints a greeting by streaming literals and the referenced string to cout.
5}The closing brace ends the body of greet.
6int main() {Defines main, the entry point where execution begins.
7 std::string user = "Ada";Creates a local string variable named user with the value Ada.
8 greet(user);Calls greet with user; the parameter simply refers to this same object.
9 return 0;Returns zero to report that the program completed successfully.
10}The closing brace ends main and the program.
Full examplecomplete
#include <iostream>
#include <string>
void greet(const std::string &name) {
    std::cout << "Hello, " << name << "!\n";
}
int main() {
    std::string user = "Ada";
    greet(user);
    return 0;
}

Worked variations

Overloads for different types

These overloads share one name and let you describe the same operation for different input types. The compiler selects the exact match at compile time, so there is no runtime branching. Notice that the string version also takes a const reference to avoid a needless copy.

Overloads for different typesvariation
#include <iostream>
#include <string>
void show(int x) { std::cout << x << "\n"; }
void show(const std::string &s) {
    std::cout << s << "\n";
}

A lambda passed to an algorithm

Here a lambda supplies custom sorting behavior right at the call site. The capture list is empty because the comparison needs nothing from its surroundings. Standard algorithms are templated on their comparator, so the compiler can inline this tiny function for maximum efficiency.

A lambda passed to an algorithmvariation
#include <algorithm>
#include <vector>
int main() {
    std::vector<int> v{5, 2, 9, 1};
    std::sort(v.begin(), v.end(),
        [](int a, int b) { return a > b; });
}

Moving a result into place

This variation shows move semantics in action. The temporary string passed to consume is not copied; its internal buffer is transferred into stored. After the call the temporary is left empty but valid, and it is destroyed normally at the end of the statement.

Moving a result into placevariation
#include <string>
#include <utility>
std::string stored;
void consume(std::string &&s) {
    stored = std::move(s);
}
int main() {
    consume(std::string("payload"));
}

Common mistakes

MistakeFix
Passing large objects by value when a const reference would doUse const std::string& or const vector& for read-only arguments to avoid copies.
Writing the same default argument in both declaration and definitionSpecify the default once in the declaration visible to callers.
Forgetting the override keyword on an intended virtual overrideAdd override so the compiler catches signature mismatches for you.
Calling a virtual function on a base object and expecting derived behaviorUse a pointer or reference to the base so dynamic dispatch can occur.
Using std::move and then reading the moved-from valueTreat a moved-from object as empty; only assign to it or let it be destroyed.

Practice

  1. Write an overload set called describe that prints an int, a double, and a std::string.
  2. Write a function append_suffix(std::string &s) that modifies its argument in place.
  3. Write a function with a default argument that computes the area of a rectangle.
  4. Use a lambda with std::sort to sort a vector of strings by length.
  5. Create a small virtual base class with two derived classes and call their override through a base pointer.
Atmospheric photograph for this chapter Curved glass and steel lattice roof Stepped white modern building corner
Build a little, often. Small programs teach more than perfect plans.

Where next