Why C++ exists and why a systems engineer should care
3 min readYou already write C, and C gives you exactly what you ask for: every byte is where you put it, every function does what you wrote, and nothing happens behind your back. That is a strength for systems work, but it is also a weakness at scale. In C, grouping data with the operations on it is a matter of convention: you write a struct, then a set of free functions that take a pointer to that struct, and you hope every caller uses the right function with the right struct and initializes the struct before using it. The compiler will not stop you from calling the wrong helper, reading an uninitialized field, or reaching inside a struct that was meant to be opaque.
C++ is the response to that gap. It started as a way to write systems code with the efficiency of C and the abstraction of a higher-level language, and it grew into the language that now runs browsers, databases, operating systems, game engines, robotics middleware and much of the automotive software stack. The key idea is the zero-overhead principle: you pay only for what you use, and an abstraction that costs nothing at run time should cost nothing. A C++ class with a constructor is, in the common case, no slower than a C struct plus a manual init function, but the language can now guarantee that the constructor ran.
Four additions in this lesson carry most of the load. A a user-defined type that bundles data members with the member functions that operate on them, together with access control replaces the loose struct-plus-functions convention. A an alias for an existing object, declared with &, that cannot be null or rebound to a different object gives you a pointer that cannot be null or accidentally reseated. A a named scope that groups related declarations so their names do not collide with names elsewhere stops unrelated libraries from fighting over the same identifier. And const correctness turns a vague promise into a rule the compiler enforces.
The embedded angle is direct. An embedded Linux system still has you touching registers, device files and raw memory, and C++ changes none of that. What changes is that you can wrap a file descriptor in a class whose destructor closes it, wrap a device register in a class that only exposes legal operations, and mark a hardware read as const so no path can silently alter state. The discipline you had to hold in your head in C becomes something the compiler holds for you.
C++ is one of the largest mainstream languages, and no engineer uses all of it. This module uses modern C++, the subset that became practical after C++11: RAII, smart pointers, templates, the standard library and const correctness. Older, error-prone constructs such as raw owning pointers, new/delete everywhere and C-style casts appear only so you can recognize and avoid them.
A short history of C++
3 min readC++ was designed by Bjarne Stroustrup at Bell Labs. In 1979 he began a project he called C with Classes, motivated by his work analysing how the Unix kernel could be distributed across a network of computers: he wanted the program organisation that classes had given him in Simula, without Simula's slowness. The direct inspiration was Simula, a language with classes, and the constraint was that the result had to stay as fast as C. The language was renamed C++ in 1983, and its first compiler, Cfront, worked by translating C++ to C, so it could run anywhere a C compiler already existed. The first edition of The C++ Programming Language appeared in 1985.
For years C++ was an evolving de facto standard with many dialects, and each compiler disagreed on details. The first international standard, ISO/IEC 14882:1998 and usually called C++98, froze the language and gave it the standard library, including the Standard Template Library of containers and algorithms. After a long quiet period, C++11 in 2011 was the turning point that created modern C++. It added move semantics, auto, lambda expressions, smart pointers, range-based for, nullptr, scoped enumerations and constexpr, and it is the reason people speak of "modern C++" as almost a different language from the older one.
The pace has since settled into a three-year cycle of feature releases: C++14 (2014), C++17 (2017), C++20 (2020) and C++23 (finalized in 2023 and published as ISO/IEC 14882:2024). The committee completed C++26 in 2026, adding static reflection and contracts; compiler support for it is still arriving, so this program targets C++20 with a few C++23 features. This lesson leans on C++17 and C++20 features such as std::string_view and std::format. Two design decisions from this history explain quirks you will meet today. First, backward compatibility with C was an explicit goal, so constructs such as NULL, unscoped enums and the default public access of struct all survive. Second, the language is standardized by consensus, so features land slowly and deliberately, which is why some obvious-seeming tools only arrived decades after the language appeared.
Explore the turning points on an interactive timeline:
Why does the history matter to a systems engineer? Because the mistakes and the diagnostic messages you will meet, an ambiguous overload, an unexpected conversion, a name that leaks from an enum, are consequences of decisions made to stay compatible with C. Understanding where the language came from is what lets you read those decisions as deliberate trade-offs rather than accidents.
From C to C++: overloading, bool, nullptr, inline functions and the ODR
5 min readThe smallest C++ programs look like C, and several changes from C show up before you write a single class. The first is defining several functions with the same name but different parameter lists, so a call resolves to the best match by argument type. In C, every function in a program needs a unique name, so you write sensor_read_int, sensor_read_float and so on. In C++, one name can serve all of them.
void report(int value);
void report(double value);
void report(const char* message);
report(42); // calls report(int)
report(3.14); // calls report(double)
report("alarm"); // calls report(const char*)
The compiler decides which function to call through overload resolution, choosing the candidate whose parameters match the arguments with the fewest conversions. Two overloads may differ only in their parameter list, never in their return type alone, because the return type is not available to disambiguate a call. Default arguments work together with overloading: a trailing parameter can be given a default, so a call may omit it.
void log_event(int code, const char* msg = "unknown");
log_event(7); // uses the default message
log_event(7, "timeout"); // supplies both
Next, C++ has a built-in boolean type. In C you use int with the macros TRUE and FALSE, or the _Bool type from C99. C++ has a real the built-in C++ boolean type with values true and false, distinct from int but convertible to it. It participates in overloading as its own type, so report(bool) and report(int) are two different functions.
The third change fixes a subtle C problem. In C, NULL is a macro, usually ((void*)0), and 0 is an int. C++ forbids the implicit conversion from void* to a typed pointer that C allows, so C++ NULL is normally defined as 0 or 0L (or, since C++11, an implementation may define it as nullptr). That makes NULL look like an integer to overload resolution. C++11 therefore introduced nullptr, a value of the dedicated type std::nullptr_t that converts to any pointer type and to pointer-to-member, but to no integral type.
void report(int value);
void report(char* message);
report(0); // calls report(int): 0 is an int
report(NULL); // calls report(int): NULL is 0 or 0L
report(nullptr); // calls report(char*): nullptr converts only to pointers
This is the classic demonstration of why nullptr exists: it disambiguates a call that 0 and NULL cannot. Always use nullptr in new C++.
The fourth change concerns inline code. In C, small helpers are often macros, which have no type checking and no scope. C++ offers inline functions instead. An inline function is a real function with real type checking, but it is given a special exemption from the one-definition rule so the same definition can live in a header included by many files. Member functions defined inside a class body are implicitly inline, which is convenient for small accessors.
That rule is central to C++. The the C++ rule that any function, variable, class or template must have exactly one definition in the whole program, with a limited inline exception says each non-inline entity may be defined once, although it may be declared many times. Define the same non-inline function in two files and the linker rejects the program. Mark it inline and identical definitions in many files collapse into one, which is how header-only utilities work.
Build the candidate set: collect every function with the name that is visible at the call site.
Keep the viable ones: drop candidates whose parameter count or types cannot accept the arguments.
Rank by conversion: prefer an exact match, then a promotion, then a standard conversion, then a user-defined conversion.
Break ties: if two candidates are equally good and neither is better than the other, the call is ambiguous and the program is rejected.
Select the best: the single best viable candidate is called.
Going deeperName mangling and how overloads reach the linker
Overloading only works because the compiler encodes each function's name plus its parameter types into a unique linker symbol. This is name mangling, and it is why a C++ function called f can coexist with ten other functions called f. On Linux, GCC and Clang follow the Itanium C++ ABI. The free function void f(int) becomes the symbol _Z1fi, and void f(double) becomes _Z1fd: _Z marks a mangled C++ name, 1f is the one-character name "f", and the trailing i or d is the parameter type code.
$ cat demo.cpp
void f(int) { }
void f(double){ }
$ g++ -c demo.cpp -o demo.o
$ nm demo.o
0000000000000000 T _Z1fd
0000000000000000 T _Z1fi
$ nm -C demo.o
0000000000000000 T f(double)
0000000000000000 T f(int)
$ c++filt _Z1fi
f(int)
This is typical output, and your addresses will differ. The -C flag demangles names, and the c++filt tool does the same on the command line. Mangling is also why calling a C function from C++ needs extern "C", a topic for the later lesson on mixing C and C++.
Recording coming soon. Follow the commands in this lesson.
class and struct: members, member functions, this and access control
3 min readIn C, a sensor is a struct plus a set of free functions that take a pointer to it. In C++ those pieces become one type. A class bundles its data members, the variables stored once per object that hold the object's state, with the member functions that operate on them.
struct Sensor {
int last_reading;
int samples_taken;
void sample() {
samples_taken++;
// read the device into last_reading
}
};
Here sample() is a member function, and inside it the names last_reading and samples_taken refer to the members of the object it was called on. The mechanism behind that is the the implicit pointer, available inside every non-static member function, that points to the object the function was called on. Writing samples_taken++ inside a member function is shorthand for this->samples_taken++. The this pointer is why a member function knows which object it belongs to, even though there is only one copy of the function's code shared by every instance.
In C++, struct and class are the same thing with one difference: their default access control. The members of a struct are public by default, and the members of a class are private by default. Access control has three levels. A public member is accessible from anywhere. A private member is accessible only from within the class's own member functions (and its friends). A protected member is like private but also accessible from derived classes, a concept the inheritance lessons cover later.
class Sensor {
public: // the intended interface
void sample();
private: // implementation detail
int last_reading = 0;
int samples_taken = 0;
};
void Sensor::sample() {
samples_taken++;
}
The public section is the interface callers may use, and the private section hides the state. A caller cannot write sensor.last_reading = 5, because last_reading is private; the compiler rejects it. This is encapsulation: the class controls its own invariants, so a caller cannot put the object into a state the author never anticipated. Member functions defined inside the class body are implicitly inline, which is convenient for small accessors; larger functions are defined out of line with Sensor:: qualification.
The choice of struct versus class is conventional. Use struct for a plain bundle of data with little or no invariant, and class for a type with an invariant you want to protect. The language treats them almost identically; the difference is a signal to the reader about intent.
The fewer members a caller can touch, the fewer states you have to reason about. Start with everything private and promote to public only the operations that the rest of the program genuinely needs. A small interface is also easier to test and to change without breaking callers.
Recording coming soon. Follow the commands in this lesson.
Constructors, destructors, member initializer lists and initialization order
4 min readThe C bug of the uninitialized struct disappears in C++ because you can give a class a a special member function, named after the class and with no return type, that runs automatically when an object is created. A constructor's job is to put every member into a valid state before any other code can observe the object. The matching a special member function named ~Class that runs automatically when an object is destroyed, releasing its resources runs when the object's lifetime ends.
Step through the lifetime of an object as a state machine:
A constructor with no parameters, or whose parameters all have defaults, is the default constructor. A constructor that takes arguments is a parameterized constructor.
class Sensor {
public:
Sensor() : last_reading(0), samples_taken(0) { } // default constructor
Sensor(int initial) : last_reading(initial), samples_taken(0) { } // parameterized
~Sensor() { /* close the device */ }
private:
int last_reading;
int samples_taken;
};
The part after the colon, before the braces, is the member initializer list. It initializes members directly. For an int the effect looks like assignment, but the distinction matters for members that cannot be assigned after the fact: a const member, a reference member, or a member of a class with no default constructor must be initialized in the list, because there is no later chance to set them.
The critical rule is the order of initialization. Members are initialized in the order they are declared in the class, not in the order you list them. If you write the list in a different order, the compiler still follows declaration order, and it warns with -Wreorder.
class Widget {
int a; // declared first, so initialized first
int b;
public:
Widget() : b(1), a(b) { } // a is initialized from b, but b is not set yet
};
Here a is declared before b, so a is initialized first, reading b while b is still uninitialized. The result is an indeterminate value in a, and GCC flags the misleading list order. The fix is to write the initializer list in declaration order, which removes the trap entirely.
1declare members in dependency order
Write the data members in the order they depend on one another. If one member is used to initialize another, declare the source of the value first. This makes declaration order and initialization order agree by construction.
2write the initializer list in declaration order
List the members in the same order you declared them. With -Wreorder enabled, the compiler will tell you the moment the two orders disagree.
3use the body only for what the list cannot do
Opening a file, logging, or validating arguments belongs in the constructor body, because the members are already initialized by then. Initializing the members themselves belongs in the list.
Allocate storage: memory for the object is obtained.
Initialize members: each data member is initialized in declaration order, using the initializer list.
Run the constructor body: the statements between the braces execute.
Live: the object is used.
Run the destructor body: its statements execute when the object dies.
Destroy members: members are destroyed in the reverse of declaration order.
Recording coming soon. Follow the commands in this lesson.
References: lvalue references, const references and references vs pointers
4 min readA reference is declared with & and is an alias, another name, for an object that already exists.
int value = 42;
int& ref = value; // ref is now another name for value
ref = 7; // value becomes 7
The reference ref does not hold a copy; it refers to value, and every read or write through ref reads or writes value. Three properties distinguish it from a pointer. A reference must be initialized at its declaration; you cannot declare an unbound reference. A reference cannot be reseated; once it refers to one object it refers to that object for its whole lifetime. And a reference cannot be null, because it always refers to an object. A pointer can be null, can be left uninitialized, and can be reassigned to point somewhere else.
A const reference adds the ability to bind to a temporary. An ordinary lvalue reference binds only to an lvalue, an object with a name and an address that outlives the expression. A const reference, or more precisely a reference to const, may also bind to an rvalue such as a literal or the result of an expression, and it keeps that temporary alive for as long as the reference lives.
int x = 1;
int& r1 = x; // ok: x is an lvalue
// int& r2 = 5; // error: cannot bind a plain reference to a temporary
const int& r3 = 5; // ok: a const reference binds to the temporary
The main use of references is in function parameters. Passing by value copies the object, which for a large object is wasteful. Passing a pointer risks a null pointer and forces call-site clutter with &. Passing by reference to const gives you the object with no copy and no risk of accidental modification.
void print_report(const std::string& s); // no copy, and s cannot be modified
The trade-off between a reference and a pointer is a table you should be able to produce from memory. A reference is the right default for a parameter that must always refer to a valid object and is not optional. A pointer is right when the object may be absent, when you need to reseat it, or when you are working with arrays and pointer arithmetic.
Going deeperReference collapsing in templates
When a template parameter is deduced, references can appear where a reference is already expected, producing a reference to a reference, which the language does not allow directly. Reference collapsing resolves it by rule: if either of the two types is an lvalue reference, the result is an lvalue reference; only rvalue-reference-to-rvalue-reference stays an rvalue reference. In short, T& &, T& && and T&& & all collapse to T&, and only T&& && collapses to T&&.
template <typename T>
void inspect(T& arg) { /* arg is always an lvalue reference */ }
This is the machinery behind forwarding references, the T&& parameter in a function template that deduces to either an lvalue or an rvalue reference depending on the argument. That topic, together with std::forward and move semantics, is the subject of the next lesson. For now the point is that references compose by these fixed rules, which is why a T& parameter behaves predictably even when T is itself deduced as a reference type.
Recording coming soon. Follow the commands in this lesson.
Namespaces, using, aliases and argument-dependent lookup
4 min readTwo independent libraries often want the same identifier. A driver library and a logging library might both define configure or reset. In C these collide at link time or silently call the wrong function. A namespace fixes this by putting each library's names in a named scope.
namespace sensor {
void configure();
int sample();
}
namespace log {
void configure();
}
int main() {
sensor::configure(); // qualified with ::
int v = sensor::sample();
}
The :: operator, the scope resolution operator, qualifies a name by naming the namespace it lives in. Inside namespace sensor { ... }, names are referred to without qualification, and the global namespace is the scope outside every namespace.
Two shortcuts bring names into view, and they are easy to confuse. A using-declaration brings one name in: using std::cout; makes cout visible unqualified, and only cout. A using-directive brings every name in: using namespace std; makes the whole std namespace visible. The using-directive is convenient in a small file but is the source of pollution and collisions, and it should never appear in a header, where it would silently affect every file that includes it.
using std::cout; // using-declaration: one name
using namespace std; // using-directive: every name (avoid in headers)
A namespace alias shortens a long or deeply nested name.
namespace fs = std::filesystem; // alias
And an unnamed namespace gives its contents internal linkage, so they are visible only within the current translation unit. This is the C++ idiom for the file-scope static of C, keeping helper names private to one file.
namespace {
int helper_state; // internal linkage, private to this file
}
The final piece of name lookup is the rule that an unqualified function call is also searched in the namespaces associated with the types of its arguments, often called ADL or Koenig lookup. For an unqualified call, ordinary lookup runs first in the current scopes, and then, if no match is found there, the compiler searches the namespaces of the argument types. This is why the stream insertion operator works without qualification.
#include <string>
#include <iostream>
int main() {
std::string name = "labpc";
std::cout << name; // operator<< found by ADL in namespace std
}
The idiomatic use is the swap pattern. A library defines a specialised swap for its own type, and generic code finds it by ADL while keeping std::swap as a fallback.
using std::swap;
swap(a, b); // finds mylib::swap by ADL, or uses std::swap
Going deeperThe hidden friend idiom constrains ADL
A friend function defined inside the class body is not visible to ordinary name lookup from outside the class; it is "hidden". It can be found only through argument-dependent lookup, and only when the class type is one of the arguments. Defining operators as hidden friends keeps the overload set small, so the operator is considered exactly when the type is involved and not for unrelated types, which reduces overload pollution and ambiguous calls.
struct Point {
int x, y;
friend bool operator==(Point a, Point b) { // hidden friend
return a.x == b.x && a.y == b.y;
}
};
// p == q finds this operator== only through ADL
The idiom pairs naturally with ADL: the function lives in the class, participates in lookup only via the class, and is never pulled in by a using-directive, so it cannot collide with other names.
Recording coming soon. Follow the commands in this lesson.
const correctness, mutable and static members
3 min readconst correctness is the practice of marking as const everything that is not meant to change. A const variable cannot be modified after initialization, and the compiler enforces that at compile time, not as a run-time convention.
const int max_samples = 1024;
// max_samples = 2048; // error: assignment of read-only variable
The same idea extends to member functions. A a member function declared with a trailing const that promises not to modify the object it is called on can be called on a const object and cannot alter the object's members. The const goes after the parameter list, which is why it is called the trailing const.
class Sensor {
public:
int reading() const { return last_reading; } // may not modify members
void set_reading(int v) { last_reading = v; } // non-const, may modify
private:
int last_reading = 0;
};
A const object may call only its const member functions, and a non-const object may call either. A member function that reads but does not write should therefore be const, so it remains callable on const objects and const references. One escape hatch exists: a member declared mutable may be modified even inside a const member function, which is used for caches and other state that does not affect the logical value of the object.
Const also has two levels, a distinction that confuses everyone once. Top-level const applies to the object itself, and low-level const applies to what a pointer points to.
int x = 0;
const int* p1 = &x; // low-level const: the pointee is const, the pointer is not
int* const p2 = &x; // top-level const: the pointer is const, the pointee is not
const int* const p3 = &x; // both
p1 can be reassigned to point elsewhere but cannot modify what it points to; p2 can modify its pointee but cannot be reassigned; p3 can do neither. Const member functions can be overloaded against non-const ones, and the correct one is chosen by the constness of the object, which is how a container offers both read and write access to the same element.
class Buffer {
public:
int& at(std::size_t i) { return data[i]; } // called on non-const
const int& at(std::size_t i) const { return data[i]; } // called on const
private:
int data[16];
};
Finally, a static data member belongs to the class as a whole, not to any instance, and is often used for counters or shared configuration. A static member function can be called without an object and can access only static members.
Going deeperStatic data members and the ODR
A static data member is declared inside the class but defined outside it, in exactly one translation unit, because it is a single object with external linkage and the one-definition rule applies.
class Sensor {
static int count; // declaration only
public:
Sensor() { ++count; }
};
int Sensor::count = 0; // the single definition, in one .cpp file
Each object increments the same count, because there is one count, not one per object. Omitting the out-of-line definition is a link-time error, an undefined reference to Sensor::count. Since C++17, a static data member can be declared inline static inside the class and then needs no separate definition, which is convenient for header-only code. A static member function such as static void reset() { count = 0; } is called as Sensor::reset() with no object and can only touch static members, because it has no this pointer.
Recording coming soon. Follow the commands in this lesson.
Type tools: auto, decltype, enum class, casts, std::string and std::format
4 min readauto lets the compiler deduce a variable's type from its initializer, which removes repetition and keeps declarations in sync with the expression.
auto x = 42; // int
auto d = 4.2; // double
auto& r = x; // int&, the reference is kept when asked for
const auto& cr = x; // const int&
By default auto drops references and top-level const, so write auto& to keep a reference and const auto& to keep const. decltype is the companion that yields the declared type of an expression without dropping those properties, which matters in generic code; its basic use is declaring a variable with the same type as an existing expression.
A an enumeration declared with enum class, whose enumerators are qualified by the type name and do not implicitly convert to int fixes two flaws of the C enum. An unscoped enum leaks its enumerators into the surrounding scope and converts to int silently, inviting accidental comparisons. A scoped enum keeps its enumerators inside the type and refuses implicit conversion, and it can name an explicit underlying type to control storage.
enum class Color : uint8_t { red, green, blue };
Color c = Color::red; // must qualify
// int n = c; // error: no implicit conversion
int n = static_cast<int>(c); // explicit, if you truly need a number
The four named casts replace the C-style cast, which is too blunt because it can silently change meaning. A static_cast performs well-defined, compile-time conversions such as int to double, and the downcast from a base to a derived pointer without a run-time check. A dynamic_cast performs a run-time-checked downcast in a polymorphic hierarchy, returning a null pointer or throwing std::bad_cast when the object is not of the target type, and it requires run-time type information. A const_cast adds or removes const, and using it to modify an object that is genuinely const is undefined behaviour. A reinterpret_cast reinterprets the bit pattern, such as treating an int* as a char*, and is implementation-defined and the last resort.
double d = static_cast<double>(n); // safe numeric conversion
int& r = const_cast<int&>(cr); // only legal if cr refers to a non-const object
For text, C++ replaces the raw char* with two library types. A std::string owns its buffer, knows its length, and manages its memory, so there is no manual free and no off-by-one counting of a terminator. Its c_str() returns a null-terminated const char* for calling C functions. A std::string_view is a non-owning view of a character sequence, a pointer plus a length, with no allocation and no requirement of null termination; the price is that it dangles if the underlying string is destroyed first.
std::string s = "sensor";
const char* c = s.c_str(); // null-terminated, valid until s changes
std::string_view v = s; // no copy, but v is invalid once s is destroyed
For output, std::format from C++20 is the type-safe replacement for printf. Where printf trusts you to match %d and %s to the arguments, std::format checks types at compile time and returns a std::string. The older iostream style, std::cout << x, is still everywhere and works through the overloaded operator<<, which is exactly the operator that argument-dependent lookup finds.
#include <format>
#include <iostream>
int main() {
int value = 42;
std::cout << "value = " << value << '\n'; // iostream
std::cout << std::format("value = {}\n", value); // C++20, type-safe
}
Recording coming soon. Follow the commands in this lesson.
Common mistakes and how to fix them
4 min readThe mistakes in this lesson cluster into a handful of recurring patterns, and the skill is to read the diagnostic, map it to the cause, and fix the source rather than the symptom.
The first is the uninitialized member read. The symptom is a garbage value in a field that looks correctly initialized, and the cause is a member initializer list written in a different order from the declarations, so one member reads another before it is set. The diagnosis is the -Wreorder warning, which flags the list order, and the fix is to order the list to match declaration order, or to initialize each member from constructor arguments instead of from another member.
The second is the forgotten const member function. The symptom is an error such as "passing const Sensor as this discards qualifiers" when you call a member function on a const object or const reference. The cause is a member function that only reads but is not declared with the trailing const. The fix is to add const, which also lets the function be called through const references.
The third is namespace pollution from a using-directive. The symptom is an ambiguous call or a silently chosen wrong overload after adding a header, and the cause is using namespace std; or its equivalent pulling hundreds of names into scope. The fix is to prefer using-declarations for the specific names you need, and never to put a using-directive in a header.
The fourth is using NULL or 0 where you mean a pointer. The symptom is that an overloaded call picks the integer overload instead of the pointer overload, and the cause is that NULL is an integer constant. The fix is to write nullptr, which converts only to pointer types.
The fifth is the C-style cast hiding a real problem. The symptom is undefined behaviour that is hard to locate, and the cause is that a C-style cast silently chooses whichever of the four conversions happens to compile, even when the choice is wrong. The fix is a named cast, which makes the intent explicit and the dangerous conversions visible.
The sixth is a dangling std::string_view. The symptom is garbage output or a crash after a function returns, and the cause is a view that refers to a std::string whose lifetime has ended, such as a view of a temporary. The fix is to keep the underlying string alive for as long as the view is used, and never to return a view of a local string.
Removing const from a reference that refers to an object that was genuinely declared const, and then writing through it, is undefined behaviour, not a clever workaround. The compiler may cache the original value, so the write appears to do nothing, or the program may crash. If a function requires a non-const reference, the object it will modify must genuinely be non-const.
Compile with -Wall -Wextra and treat warnings as errors in new code with -Werror. The warnings around initialization order, implicit conversions and unused results catch most of the mistakes in this list before they become bugs, and they cost nothing at run time.
Try it
1 min readCompile the small class examples from this lesson with g++ -Wall -Wextra -std=c++20, then build the three labs from the practice pack. Refactor the C sensor program, a struct plus free functions, into a class with private data and a small public interface, and confirm the callers still compile unchanged. Write a namespace-collision example where two namespaces define the same function name, and resolve it with a using-declaration and a namespace alias, then watch operator<< on a std::string work because of argument-dependent lookup. Finish with the const-correctness exercise: mark the read-only member functions const, fix the initialization-order bug with -Wreorder, and read the compiler diagnostics until they are clean. Use nm and c++filt on your overloaded functions to see the mangled symbols behind overloading.
Key takeaways
- C++ keeps C's control and speed but adds abstractions that the compiler can check instead of relying on discipline.
- Function overloading lets one name serve several argument types, resolved to the best match at compile time.
- A class bundles data with the functions that operate on it, and access control enforces the intended surface.
- Constructors initialize members in declaration order, not in the order you write in the initializer list.
- A reference is an alias that cannot be null or reseated; a const reference can also bind to a temporary.
- Namespaces prevent name collisions, and argument-dependent lookup finds the right function in an operand's namespace.
- const correctness makes intent explicit, and const member functions can be overloaded against non-const ones.
- auto, enum class, the named casts, std::string and std::format replace the weaker C idioms you already know.
Reflect
- Explain to a colleague, in two sentences: explain why C++ adds classes, references, namespaces and const to C, and the problem each one solves.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Official docscppreference, C++ language reference
- Official docscppreference, Overload resolution
- Official docscppreference, Reference declaration
- Official docscppreference, Argument-dependent lookup
- Official docscppreference, cv (const and volatile) type qualifiers
- Official docscppreference, C++ Standard Library, std::string and std::format
- SpecificationItanium C++ ABI (name mangling rules)
- SpecificationISO/IEC 14882 C++ working draft N4950
- Man pagec++filt(1) man page
Official documentation first. Links checked when the lesson was published.