Programming Languages
Modern C++ from first program to templates, idioms, toolchains, build systems and libraries.
A path through modern C++ for developers who want systems-level control with high-level abstractions. It starts with syntax, types and memory, moves through classes, templates and the standard library, and finishes with the toolchain around the language: compilers, debuggers, CMake, package managers and popular libraries. Each subject links the official documentation.
The subjects follow the roadmap.sh C++ roadmap.
C++ is a compiled, statically typed systems language that gives you direct control over memory and hardware while still offering classes, templates and a large standard library. It is standardised by ISO and evolves on a three-year release cycle.
A multi-paradigm language created by Bjarne Stroustrup as "C with Classes". It mixes procedural, object-oriented and generic programming and follows the zero-overhead principle: you do not pay for features you do not use.
Chosen where performance and predictable latency matter: game engines, browsers, databases, trading systems, embedded firmware and compilers. You get deterministic destruction and no garbage collector, at the price of more responsibility for correctness.
C++ grew out of C and can call C code via extern "C", but it is not a strict superset: implicit void* conversions, designated initializers and some keywords differ. Idiomatic C++ prefers RAII, references and containers over manual malloc/free.
You need a compiler toolchain, an editor that understands C++ and a way to build and run programs. On Linux that is usually GCC or Clang from the package manager, on macOS the Xcode command line tools, and on Windows Visual Studio or MinGW-w64.
Install a toolchain rather than "C++" itself: build-essential or clang on Linux, xcode-select --install on macOS, the "Desktop development with C++" workload or MSYS2 on Windows. Check with g++ --version or clang++ --version.
Visual Studio, CLion and Qt Creator are full IDEs; VS Code or Neovim plus clangd give completion, diagnostics and refactoring in a lighter editor. A compile_commands.json file lets language servers see your real build flags.
Write a main function that prints with std::cout, compile with g++ -std=c++20 -Wall -Wextra hello.cpp -o hello and run ./hello. Turn warnings on from day one; they catch many beginner bugs.
Operators combine values into expressions. Learn their precedence and associativity, the difference between integer and floating-point arithmetic, and which operations can overflow or trigger undefined behaviour.
+ - * / % plus increment and decrement. Integer division truncates toward zero, % follows the sign of the left operand, and signed overflow is undefined behaviour, so pick types wide enough for your values.
&&, || and ! work on bool and short-circuit: the right side is evaluated only when needed, so p && p->ok() is safe. Overloading them loses the short-circuit behaviour, which is why it is discouraged.
& | ^ ~ << >> manipulate individual bits for flags, masks and packed data. Use unsigned types; shifting by the bit width or more, or left-shifting negative numbers before C++20, is undefined. C++20 adds <bit> helpers like std::popcount.
Statements decide which code runs and how often. Beyond the classic branches and loops, modern C++ adds range-based for, init-statements inside if and switch, and if constexpr for compile-time branching.
if/else handles general conditions; switch jumps on integral or enum values and falls through unless you break (mark intended fall-through with [[fallthrough]]). goto exists but is rarely justified outside breaking from nested loops.
for suits counted loops, range-based for (auto& x : v) iterates containers, while checks before each pass and do/while runs at least once. Watch out for modifying a container while iterating over it.
Functions are declared with a return type, a name and parameters passed by value, reference or pointer. Learn default arguments, inline, constexpr, trailing return types, and when to pass by const& versus by value.
Several functions can share a name if their parameter lists differ; the compiler picks the best match during overload resolution. Ambiguities and surprising implicit conversions are the usual pitfalls.
Give user types natural syntax by defining operator+, operator==, operator<< and friends. Keep semantics unsurprising; since C++20, defaulting operator<=> generates all the comparison operators for you.
Anonymous function objects written inline: [capture](params) { body }. Capture by value or reference, use mutable to modify copies, and avoid capturing references that outlive their scope. Generic lambdas take auto parameters.
Fundamental types (int, double, char, bool), compound types (arrays, pointers, references) and user-defined types make up the type system. Sizes are implementation-defined, so use <cstdint> types like std::int32_t when width matters.
Every expression has a type known at compile time, so type errors surface before the program runs and the compiler can optimise aggressively. auto and templates reduce verbosity without giving that up.
C++ has no dynamic typing in the language, but the library offers runtime-flexible holders: std::any for any copyable value, std::variant for a closed set of types, and void* as the unsafe legacy option.
Run-time type information lets typeid and dynamic_cast inspect the real type of a polymorphic object. It costs some binary size, and some projects disable it with -fno-rtti.
Pointers hold addresses and can be null or reseated; references are aliases that must bind to an object. Owning memory through raw pointers is the classic source of leaks and crashes, which is why modern code uses smart pointers and RAII.
An lvalue reference T& is another name for an existing object; const T& can also bind temporaries. Rvalue references T&& enable move semantics and perfect forwarding. A reference to a destroyed object dangles.
Objects live in automatic (stack), static, thread-local or dynamic (heap) storage. The formal memory model also defines how threads see each other's writes, which is what makes data races undefined and atomics meaningful.
An object's lifetime starts when initialisation completes and ends when its destructor runs. Locals die at the end of scope in reverse order; temporaries usually die at the end of the full expression unless bound to a const&.
A plain T* is fine as a non-owning, possibly null observer. Avoid using it to own memory, never return pointers to locals, and prefer nullptr over NULL or 0.
new allocates and constructs, delete destroys and frees; arrays need new[]/delete[] and mixing them is undefined. In modern code you almost never write them directly, using std::make_unique and containers instead.
Memory leaks when the last pointer to a heap allocation is lost without freeing it, often on an early return or exception. Find them with LeakSanitizer (-fsanitize=address) or Valgrind, and prevent them with RAII.
Class templates in <memory> that own a heap object and free it automatically. They express ownership in the type: unique, shared, or a non-owning weak observer of shared state.
Sole ownership with zero overhead over a raw pointer. It is move-only, so ownership transfers explicitly with std::move. Create one with std::make_unique<T>(args...); it should be your default owning pointer.
Shared ownership through an atomic reference count; the object dies when the last owner goes. Use std::make_shared for one allocation, and only reach for it when ownership is genuinely shared.
A non-owning handle to an object managed by shared_ptr. Call lock() to get a temporary shared_ptr if it still exists. It breaks reference cycles such as parent and child pointing at each other.
Real programs span many files. Declarations go in headers, definitions in source files, names are grouped into namespaces, and the one-definition rule ties it together. C++20 modules are the newer alternative to header inclusion.
Scope controls where a name is visible: block, function, class, namespace or global. Inner names shadow outer ones, and keeping variables in the smallest scope keeps code easier to reason about.
Named scopes that prevent name clashes between libraries, like std::. Avoid using namespace in headers, use anonymous namespaces for file-local helpers, and nest with namespace a::b {}.
Headers declare the interface and are pulled in by #include; .cpp files hold definitions and are compiled separately into object files. Protect headers with #pragma once or include guards.
Declaring class Foo; without its definition lets you use pointers and references to it. It cuts header dependencies and compile times, and breaks circular includes, but you cannot access members until the full type is visible.
struct and class both define types with data members, member functions, constructors and destructors; they differ only in default access. Here you learn encapsulation, inheritance, polymorphism and the special member functions that control copying and moving.
Bundle state with the functions that maintain its invariants, hide details behind private, and model is-a relationships with inheritance. In C++ OOP is one tool among several, often mixed with value types and generic code.
Choosing behaviour at compile time through overloading, templates and CRTP. No virtual call overhead and full inlining, at the cost of code bloat and errors that appear at instantiation time. C++20 concepts make the requirements explicit.
Calling through a base-class pointer or reference and getting the derived behaviour at runtime. It requires virtual functions and always a virtual destructor in a polymorphic base class.
Member functions marked virtual can be overridden in derived classes. Mark overrides with override, block further overriding with final, and use = 0 for pure virtual functions that make a class abstract.
The usual implementation of virtual dispatch: each polymorphic class has a table of function pointers and each object a hidden pointer to it. A virtual call is an indirect call that usually cannot be inlined.
A class can derive from several bases, most usefully to implement several abstract interfaces. Name clashes and pointer adjustments between bases make it trickier than single inheritance.
When two bases share a common ancestor the derived class gets two copies of it. Virtual inheritance (class B : virtual public A) keeps a single shared subobject, and the most-derived class then constructs it.
If a class manages a resource it needs a destructor, copy constructor and copy assignment (three), plus move constructor and move assignment (five). Better still, let members such as smart pointers own resources and write none of them (zero).
Errors are reported with throw and handled with try/catch; during unwinding destructors run, which is why RAII and exceptions fit together. Know the exception-safety guarantees, mark non-throwing functions noexcept, and consider std::expected (C++23) for expected failures.
Throw by value, catch by const&, and derive custom types from std::exception or std::runtime_error. An exception escaping a noexcept function or a destructor calls std::terminate.
The value returned from main or passed to std::exit becomes the process status; 0 or EXIT_SUCCESS means success. Shells and CI pipelines rely on it, and std::exit skips destructors of local objects.
Reading or writing memory the process does not own, such as through a null, freed or out-of-bounds pointer, crashes with a segmentation fault or access violation. AddressSanitizer pinpoints the faulting line and the allocation involved.
Rules that cut across everything else: type deduction, the cast operators, how names are looked up, what the preprocessor does, and which code has no defined meaning at all. These explain many confusing compiler errors and runtime bugs.
auto deduces a variable's type from its initialiser using template deduction rules, so it drops references and top-level const unless you write auto& or const auto&. decltype(auto) keeps the exact type.
C++ splits the all-powerful C cast into four named casts that state intent and are easy to search for. Prefer them to (T)x, and treat each cast as a design smell worth a second look.
Compile-time checked conversions: numeric types, enums, void* back to a typed pointer, and up or down a class hierarchy without a runtime check. A wrong downcast is undefined behaviour.
Adds or removes const or volatile. Mostly for calling legacy APIs that forgot const; modifying an object that was originally declared const is undefined behaviour.
A runtime-checked downcast in polymorphic hierarchies: it returns nullptr for pointers or throws std::bad_cast for references when the object is not of the target type. It needs RTTI and is slower than static_cast.
Reinterprets bits, such as a pointer as an integer or one unrelated pointer type as another. It is the least safe cast; accessing the result often breaks strict aliasing, and std::bit_cast (C++20) is the safe way to copy object bits.
Code the standard gives no meaning to, like signed overflow, out-of-bounds access or data races. The optimiser assumes UB never happens, so effects can be bizarre and far from the cause. UBSan (-fsanitize=undefined) catches many cases.
Unqualified function calls also search the namespaces of the argument types. That is why std::cout << x finds the right operator<<, and why the using std::swap; swap(a, b); pattern picks custom overloads.
Compilers encode namespaces, classes and parameter types into symbol names so overloads can coexist in the linker. c++filt decodes them, and extern "C" turns mangling off for C interop.
Text substitution done by the preprocessor before compilation, ignoring scope and types. Still needed for include guards and conditional compilation, but prefer constexpr, inline functions and templates for everything else.
The standard library ships containers, iterators and algorithms (the original STL), plus strings, streams, smart pointers, time, threads and more. Knowing it well removes most reasons to write raw loops or manual memory management.
std::vector is the default; also array, deque, list, ordered map/set (trees) and unordered_map/unordered_set (hash tables). Learn their complexity guarantees and which operations invalidate iterators.
Generalised pointers that connect containers to algorithms. Categories range from input to contiguous iterators; C++20 ranges add sentinels and views so you can write std::ranges::sort(v).
<algorithm> and <numeric> provide sorting, searching, partitioning, transforming and accumulating over iterator ranges. Using std::find_if or std::transform instead of hand-written loops makes intent obvious.
Type-safe stream I/O with std::cout, std::cin and file streams. Prefer '\n' over std::endl to avoid needless flushes; for formatting, C++20 std::format and C++23 std::print are faster and clearer.
<chrono> models durations, clocks and time points with type-checked units. Use steady_clock for measuring elapsed time, system_clock for wall time; C++20 adds calendars and time zones.
std::thread and std::jthread, std::mutex with std::lock_guard or std::scoped_lock, condition variables, std::atomic and std::async/std::future. Any unsynchronised concurrent write is a data race; ThreadSanitizer finds them.
Templates let you write a function or class once for many types; the compiler generates a concrete version per instantiation. They power the standard library and compile-time programming, and C++20 concepts finally give them readable constraints.
Templates taking any number of arguments through parameter packs (typename... Ts). Expand packs with args... and, since C++17, fold expressions like (args + ...); perfect forwarding uses std::forward<Ts>(args)....
Supplying a different implementation of a template for particular arguments, such as a compact vector<bool>. Specialisations must be declared before first use and live in the same namespace as the primary template.
Every template parameter is fixed: template<> struct Hash<MyType> { ... };. Works for both class and function templates, though for functions plain overloading is usually the better choice.
Only some parameters are fixed or constrained, such as a version for all pointer types template<class T> struct X<T*>. It applies to class and variable templates only, not to function templates.
<type_traits> answers questions about types at compile time (std::is_integral_v<T>) and transforms them (std::remove_reference_t<T>). Combined with if constexpr and concepts it drives generic code.
Substitution failure is not an error: when deducing template arguments produces an invalid type, that overload is quietly dropped. It enabled std::enable_if tricks; C++20 requires clauses do the same job far more readably.
Recurring C++ patterns that solve problems the language leaves open: ownership, exception safety, ABI stability and compile-time polymorphism. Recognising them makes library code and code reviews much easier to follow.
Resource acquisition is initialisation: acquire a resource in a constructor and release it in the destructor, so cleanup happens on every exit path including exceptions. Smart pointers, std::lock_guard and file streams all work this way.
Types that represent a unique resource, like a mutex, should not be copied. Declare the copy constructor and copy assignment = delete; deleting copies also suppresses the implicit move operations.
std::remove_if only shuffles kept elements to the front and returns the new logical end; you then call erase to shrink the container. C++20 replaces the dance with std::erase_if(container, pred).
Implement assignment by taking the argument by value and swapping it with *this. The copy happens before anything changes, which gives the strong exception guarantee and handles self-assignment for free.
Copies share one buffer until someone writes, at which point the writer makes a private copy. Standard strings stopped doing it in C++11 because it clashed with threads and iterator rules, but it still appears in Qt containers.
Pointer to implementation: the public class holds only a std::unique_ptr<Impl> and the real members live in the .cpp file. It hides private details, shortens rebuilds and keeps a stable ABI, for the cost of an extra allocation and indirection.
The curiously recurring template pattern: class D : public Base<D>. The base can call derived members through static_cast<D&>(*this), giving polymorphism without virtual calls. C++23 explicit object parameters ("deducing this") simplify it.
ISO committee WG21 publishes a new C++ standard every three years. Compilers adopt features gradually, so you choose a standard with -std=c++20 or /std:c++20 and check support tables before relying on new features.
The working name of the standard that eventually shipped in 2011 as C++11; the "x" was expected to be a digit before 2010. You will still see the name in old articles and in flags like -std=c++0x.
The start of modern C++: move semantics, auto, lambdas, range-based for, nullptr, smart pointers, constexpr and a threading library. C++14 polished it with generic lambdas, make_unique and relaxed constexpr.
Structured bindings, if constexpr, fold expressions, class template argument deduction, std::optional, std::variant, std::string_view, std::filesystem and parallel algorithms.
A release as big as C++11: concepts, ranges, coroutines, modules, the three-way comparison operator, std::span, std::format and calendar support. Module and coroutine tooling still varies between compilers.
Deducing this, std::expected, std::print, std::mdspan, std::flat_map, more ranges adaptors and import std; for the whole standard library as a module.
A debugger lets you pause a running program, step through it, inspect variables and examine crashes and core dumps. Build with debug info and low optimisation (-g -O0, or -Og) when you want stepping to match the source.
Learn to read signals like SIGSEGV and SIGABRT, stack traces with frame numbers, "optimized out" variables and assertion failures. The top user-code frame in a backtrace is usually where to start looking.
Debug information (DWARF on Linux and macOS, PDB files on Windows) maps machine code back to source lines and variables. Release builds can keep it in separate files so crash dumps stay readable without shipping it.
The GNU debugger: break, run, next, step, bt, print and watch cover most sessions. It also opens core dumps (gdb ./app core) and attaches to running processes.
Microsoft's debugger for Windows user-mode and kernel-mode code and crash dumps. The !analyze -v command gives a first diagnosis of a dump; it pairs with PDB symbol servers.
The compiler turns source into object files and the linker joins them into a program. The major toolchains differ in diagnostics, optimisation, standard support and platforms, so testing with more than one catches non-portable code.
Preprocessing expands includes and macros, compilation turns each translation unit into assembly, the assembler produces object files and the linker resolves symbols across them. -E, -S and -c stop after each stage.
Toolchains offer warnings (-Wall -Wextra), optimisation levels, sanitizers, link-time optimisation and their own extensions. Each publishes a table of which standard features it supports.
The GNU Compiler Collection, default on most Linux distributions. g++ drives the C++ front end; it has broad target support and its own standard library, libstdc++.
Clang is the C/C++ front end of the LLVM project, the default on macOS and widely used elsewhere. It is known for clear diagnostics and tooling built on it: clang-tidy, clang-format and clangd.
Microsoft's compiler cl.exe, shipped with Visual Studio and the Build Tools. It is the standard choice for Windows-native and DirectX work and has its own flag syntax like /W4 and /std:c++latest.
Intel's LLVM-based oneAPI compiler (icx) focuses on optimisation for Intel CPUs and GPUs and on SYCL/OpenMP offloading. Mostly relevant in HPC and numeric code.
MinGW-w64 ports GCC to produce native Windows binaries without Visual Studio, usually installed through MSYS2. Handy for cross-platform projects that want the same compiler everywhere.
Compiling files by hand stops scaling quickly. A build system tracks dependencies, rebuilds only what changed and handles flags per platform. CMake is the de facto standard for describing C++ projects and generates Make or Ninja files.
Write CMakeLists.txt with targets (add_executable, add_library) and attach settings with target_link_libraries and target_compile_features. Configure with cmake -S . -B build, then build with cmake --build build.
GNU Make runs recipes when targets are older than their prerequisites. Fine for small projects and the classic CMake output; tabs in recipes and header dependency tracking are the usual gotchas.
A minimal, very fast build executor designed to be generated rather than hand-written. Use cmake -G Ninja for quicker incremental builds and automatic parallelism.
C++ has no single official package manager. Tools differ in whether they build from source or ship binaries and how they integrate with CMake, so pick one per project and pin versions.
Microsoft's source-based manager with a large curated catalogue. Declare dependencies in vcpkg.json and pass its CMake toolchain file; binary caching avoids rebuilding the same packages.
The .NET package manager, which can also deliver native C++ packages into Visual Studio projects. Mostly useful when you are already in the MSBuild ecosystem.
A decentralised, binary-oriented manager written in Python. Recipes describe how to build packages, and binaries are cached per configuration (compiler, flags, OS), which suits large teams with private remotes.
A package manager built for supercomputers and scientific software, able to install many variants of the same library side by side with different compilers and MPI implementations.
Using third-party code means finding headers, linking static or shared libraries and respecting their licences. Learn the difference between .a/.lib and .so/.dll, and let your build system locate packages instead of hard-coding paths.
In CMake, find_package(Foo REQUIRED) then target_link_libraries(app PRIVATE Foo::Foo) brings in include paths and link flags together. FetchContent pulls sources directly; header-only libraries just need an include path.
Check a library's licence before shipping it. Permissive licences (MIT, BSD, Boost, Apache-2.0) mostly need attribution; GPL requires releasing your source when you distribute, and LGPL is easiest to honour via dynamic linking.
Well-known libraries worth recognising. Most C++ jobs use a handful of them, so learn the ones your domain needs: Boost and fmt are broadly useful, the others are specialised.
A large collection of peer-reviewed libraries (Asio, Beast, Filesystem, Program Options, Container and more); many standard features like smart pointers and optional started here. Most parts are header-only.
Fast, type-safe formatting with Python-like {} placeholders; it became the basis of std::format and std::print. Still useful on compilers without full C++20/23 support.
A fast logging library built on fmt, with sinks for console, rotating files and syslog, plus an async mode. It can be used header-only or compiled.
Eric Niebler's range library that became the basis for C++20 <ranges>. It still offers views and actions the standard lacks, and works on older compilers.
Portable components for networked applications: HTTP clients and servers, sockets, JSON and XML, data access and threading, wrapped in a consistent class-based API.
Google's Protocol Buffers: define messages in .proto files and protoc generates C++ classes with compact binary serialisation and backward-compatible schema evolution.
An RPC framework over HTTP/2 that generates client stubs and server interfaces from protobuf service definitions. The C++ API offers sync, callback and async styles.
Header-only library for exposing C++ functions and classes to Python, or embedding Python in C++, with automatic conversion of STL types and NumPy arrays.
The standard computer vision library: image I/O, filtering, feature detection, camera calibration and a DNN module for running trained models, centred on the cv::Mat type.
A Khronos standard for running compute kernels on GPUs, CPUs and accelerators from different vendors. The host code in C or C++ sets up devices, buffers and command queues.
TensorFlow is written in C++ and has a C++ API for building and running graphs, mostly used to deploy trained models; LiteRT (formerly TensorFlow Lite) targets mobile and embedded devices.
Larger frameworks that shape how a whole application or test suite is written: testing, GUI, profiling and machine learning. Pick by domain; every C++ developer should at least know one unit testing framework.
GoogleTest provides TEST and TEST_F fixtures with EXPECT_*/ASSERT_* checks; GoogleMock adds mock classes via MOCK_METHOD and call expectations. CMake's gtest_discover_tests wires them into CTest.
A test framework with natural TEST_CASE and SECTION blocks and expression-decomposing REQUIRE(a == b) that prints both sides on failure. Also includes micro-benchmarking.
A cross-platform application framework for desktop, mobile and embedded GUIs (Widgets and QML), with its own containers, signals and slots and a meta-object compiler. Available under LGPL/GPL or a commercial licence.
An open-source sampling and instrumentation profiler originally from Google, for finding hot spots in native code without modifying it much. Development has slowed, so consider perf or Tracy too.
LibTorch is PyTorch's C++ front end: tensors, autograd and modules that mirror the Python API, plus loading TorchScript models for inference without Python.