C++ Tutorial
Learn modern C++ from the basics to classes, templates, the STL, smart pointers, concurrency and C++23. 171 lessons with real code compiled in your browser, quizzes and projects.
Start learning →
of lessons completed
Getting Started
- Getting Started with C++ Learn what C++ is, where it's used and why it's still everywhere. Write, compile and run your first modern C++ program with std::println, right in your browser.
- How C++ Works: Compiling and Linking Follow C++ code from source to executable through the preprocessor, compiler and linker. Meet GCC, Clang, MSVC, C++ standards, warnings and UB.
- C++ Syntax Learn the core rules of C++ syntax: main, statements, semicolons, blocks, #include, namespaces, std::, using declarations and reading compiler errors.
- Comments Write clear C++ comments with // and /* */, document functions Doxygen-style, avoid the nesting and backslash traps, and learn which comments help.
- Printing Output Print text and values in C++ with std::println, std::print and format strings, use std::cout with <<, prefer '\n' to std::endl, and write to std::cerr.
- Reading User Input Read numbers, words and whole lines in C++ with std::cin and std::getline, fix the leftover-newline bug, validate input and loop until input ends.
- Keywords and Identifiers See every C++ keyword grouped by purpose, learn the rules for valid identifiers, compare naming styles and avoid names reserved for the compiler.
- Dependencies with vcpkg and Conan Learn how C++ package managers work. Use vcpkg manifests and Conan recipes with CMake, pin versions, understand triplets and profiles, and see how dependency resolution works.
Variables and Types
- Variables Declare and initialize C++ variables with =, () and {} braces, see why uninitialized variables are dangerous, assign new values and preview scope.
- Fundamental Data Types Learn the C++ fundamental types (bool, char, int, double, void), how big they really are with sizeof, fixed-width types from <cstdint> and numeric_limits.
- Integer Types Master C++ integers - signed vs unsigned ranges, overflow (undefined vs wrapping), signed/unsigned comparison traps, std::size_t, and hex, binary and suffixed literals.
- Floating-Point Numbers Learn C++ float, double and long double, why 0.1 + 0.2 != 0.3, how to compare floating-point values safely, NaN and infinity, and std::numbers constants.
- Characters and Booleans Learn how C++ char really works (a small integer, signed or not), ASCII arithmetic, <cctype> pitfalls, char8_t/char16_t/char32_t, and bool conversions.
- Type Deduction with auto Learn exactly what C++ auto deduces, why it drops const and references, when to use auto&, const auto& and auto&&, how decltype differs, and when auto helps readability.
- Constants: const, constexpr and consteval Learn C++ constants - const for values that never change, constexpr for compile-time values and functions, consteval and constinit, and why #define constants are a bad idea.
- Type Conversions and Casts Learn how C++ converts types implicitly (promotions, arithmetic conversions), how brace init stops narrowing, how to use static_cast, and why C-style casts are risky.
- Type Aliases: using and typedef Learn C++ type aliases with using and the legacy typedef, alias templates, member type aliases like value_type, and why an alias is not a new type.
- Math Functions Use C++ math functions from <cmath> and <numeric>, pow, sqrt, rounding, trig, gcd, lcm, std::numbers, and integer division and remainder with negatives.
Operators
- Arithmetic Operators Learn the C++ arithmetic operators + - * / %, integer vs floating-point division, the modulo operator, type promotion rules and how integer overflow bites.
- Assignment and Increment Operators Master C++ assignment, compound assignment like += and *=, prefix vs postfix ++ and --, and the sequencing rules that make code like i = i++ so dangerous.
- Comparison and Logical Operators Compare values in C++ with == != < > <= >=, use the C++20 three-way comparison <=>, and combine conditions with &&, || and ! using short-circuit evaluation.
- Bitwise Operators Learn the C++ bitwise operators & | ^ ~ << >>: masks, setting and clearing bits, shift rules, enum flags, std::bitset and C++20 <bit> functions like popcount.
- Operator Precedence and the Conditional Operator The full C++ operator precedence and associativity table, how evaluation order differs, the ?: conditional operator, the comma operator, sizeof and ::.
Strings
- Strings with std::string Learn C++ std::string from scratch, creating and joining strings, size and length, indexing with [] and at(), comparing, and looping over text.
- String Methods A practical guide to C++ std::string methods: find and rfind, npos, substr, replace, insert, erase, append, starts_with, ends_with, contains, resize and c_str.
- std::string_view Learn C++ std::string_view - cheap non-owning views of text, the best string parameter type, substr without copying, remove_prefix, and the dangling-view traps.
- Formatting with std::format and std::print The complete guide to C++ std::format and std::println - width, fill, alignment, precision, signs, hex and binary, formatting vectors and maps, custom formatters, iomanip.
- Converting Between Strings and Numbers Convert between strings and numbers in C++ - std::to_string, stoi and stod with their exceptions, fast from_chars and to_chars, std::format, and safe parsing helpers.
- C-Style Strings and Character Arrays Understand C-style strings in C++ - char arrays, the null terminator, strlen, strcpy, strcmp and snprintf, buffer overflows, and converting to and from std::string.
- Locales and Unicode Text Understand how C++ handles text beyond ASCII. Use std::locale and facets for number formatting, work with UTF-8 bytes and code points, decode and validate text, and avoid common pitfalls.
Control Flow
- if, else if and else Learn C++ if, else if and else - how conditions convert to bool, else-if chains, nesting and guard clauses, if with an initializer (C++17), if constexpr and common bugs.
- switch Statements Learn the C++ switch statement - case labels, break and fall-through, [[fallthrough]], switching on enums, switch with an initializer, case scope rules and when to use it.
- while and do-while Loops Learn C++ while and do-while loops - how conditions are checked, input loops that read until end of input, validation loops, infinite loops with break and loop bugs.
- for Loops and Range-Based for Learn C++ for loops - classic counting loops, range-based for by value, reference and const reference, loops with an initializer (C++20), views::enumerate and nested loops.
- break, continue and goto Learn how break and continue control C++ loops, how to exit nested loops cleanly with functions, flags and lambdas, and why goto is almost never the answer.
Arrays and Vectors
- C-Style Arrays Learn C-style arrays in C++ - declaring, initializing and indexing, why there is no bounds checking, how arrays decay to pointers, and when to use std::array instead.
- std::array Learn std::array, the zero-cost fixed-size array of modern C++ - creating it, at() vs [], size(), fill, iteration, copying, comparison and passing it to functions.
- std::vector Learn std::vector, the dynamic array of C++ - creating vectors, push_back and emplace_back, size vs capacity, reserve, insert and erase, iteration and common pitfalls.
- Multidimensional Arrays and Matrices Store grids and matrices in C++ with 2D arrays, std::array of arrays, vector of vectors and fast flat vectors with index math, plus row-major order and std::mdspan.
- std::span Learn std::span (C++20) - one function for C arrays, std::array and std::vector, read-only vs writable spans, subspan, fixed vs dynamic extent, and dangling-span pitfalls.
Functions
- Functions Learn C++ functions - defining and calling them, return types and void, declarations vs definitions, how calls work, [[nodiscard]], and how to design small, clear functions.
- Parameters: by Value, by Reference and by const Reference Learn how to pass arguments in C++ - by value, by reference and by const reference, what each costs, output parameters and better alternatives, and passing strings and vectors.
- Default Arguments Learn C++ default arguments - giving parameters default values, the trailing-defaults rule, where to declare defaults, evaluation rules, and when overloads are better.
- Returning Values Return values the modern C++ way - return by value and copy elision, multiple results with structs, pairs, tuples and structured bindings, std::optional, and dangling references.
- Function Overloading Learn C++ function overloading - which signatures can overload, how the compiler ranks candidates, why calls become ambiguous, and when to use templates instead.
- inline Functions What inline really means in modern C++ - the one-definition rule, defining functions and variables in headers, implicit inline, C++17 inline variables, and optimizer inlining.
- Recursion Learn recursion in C++ - base and recursive cases, how the call stack works, factorial, Fibonacci and fast power, stack overflow, tail calls, loops vs recursion and memoization.
- Scope, Lifetime and Storage Duration Understand C++ scope and lifetime - block and global scope, shadowing, automatic, static, dynamic and thread storage duration, static local variables, and global variable pitfalls.
- Namespaces Learn C++ namespaces - defining and reopening them, nested a::b namespaces, aliases, using declarations vs directives, anonymous namespaces, ADL, and the rules for std.
- Header Files and Multiple Source Files Split C++ programs into .h and .cpp files - what goes in a header, include guards and #pragma once, the one-definition rule, how the linker joins files, and modules.
- The Preprocessor and Macros Learn the C++ preprocessor - #define macros and their pitfalls, # and ##, conditional compilation, predefined macros, #warning, __has_include and feature-test macros.
- Function Pointers and std::function Learn C++ function pointers - declaration syntax, callbacks, arrays of functions, std::function, and how they compare with templates and lambdas.
- Callbacks: Function Pointers, std::function and Lambdas Design callbacks in C++: compare function pointers, templates and std::function, pass state safely, unsubscribe with RAII handles, handle exceptions and use move_only_function.
Pointers, References and Memory
- References Learn C++ references - lvalue references as aliases, references as parameters and return values, const references binding temporaries, and dangling pitfalls.
- Pointers Learn C++ pointers from scratch - addresses, the & and * operators, nullptr, pointers to structs with ->, pointers to pointers, and why null dereference is UB.
- Pointers and Arrays Learn C++ pointer arithmetic - how arrays decay to pointers, p + n and p[n], pointer differences, one-past-the-end, comparison rules and iterating with pointers.
- const with Pointers and References Learn C++ const with pointers and references - pointer to const vs const pointer, reading declarations right to left, const_cast dangers and const correctness.
- Dynamic Memory: new and delete Learn C++ dynamic memory - heap allocation with new and delete, new[] and delete[], memory leaks, double delete, dangling pointers and why modern code avoids raw new.
- Smart Pointers: std::unique_ptr Learn C++ std::unique_ptr - exclusive ownership, std::make_unique, moving ownership, passing to functions, custom deleters, arrays and polymorphic objects.
- Smart Pointers: shared_ptr and weak_ptr Learn C++ std::shared_ptr and std::weak_ptr - shared ownership, make_shared, reference counts, breaking cycles with weak_ptr, costs, and choosing a smart pointer.
- Memory Leaks: Causes, Detection and Prevention Learn how memory leaks happen in C++ - early returns, exceptions, lost pointers, owning containers, constructors that throw - and how RAII, smart pointers and LeakSanitizer fix them.
- Memory Layout: Stack, Heap and Objects See how C++ lays out memory - stack, heap and static storage, object size, alignment and padding, sizeof of classes, alignas, and why contiguous data is fast.
- Undefined Behavior and Memory Safety Understand undefined behavior in C++ - what it is, why optimizers exploit it, the common causes like out-of-bounds and use-after-free, and how sanitizers catch them.
Object-Oriented Programming
- Object-Oriented Programming in C++ An overview of object-oriented programming in C++ - classes and objects, encapsulation, inheritance, polymorphism and abstraction, and how OOP fits C++'s multi-paradigm style.
- Classes and Objects Learn to define C++ classes - member variables and functions, creating objects, the dot and arrow operators, struct vs class, and defining member functions outside the class.
- Constructors and Member Initializer Lists Master C++ constructors - default and parameterized constructors, member initializer lists and their order, default member initializers, delegating constructors, explicit and = default.
- Destructors and RAII Learn C++ destructors and RAII - when objects are destroyed, destruction order, wrapping files and locks in classes, cleanup during exceptions, and why RAII beats finally.
- Access Specifiers and Encapsulation Learn C++ access specifiers - public, private and protected, getters and setters done right, class invariants, leaking internals by reference, and designing clean class interfaces.
- The this Pointer Understand the C++ this pointer - how member functions find their object, this-> for shadowed names, returning *this for chaining, capturing this in lambdas, and C++23 deducing this.
- const Member Functions and mutable Learn C++ const member functions - const objects, why getters must be const, const overloading of operator[], mutable caches, and const-correctness pitfalls.
- Static Members Learn C++ static members - class-wide data, inline static and constexpr static members, static member functions, instance counters, and why singletons cause trouble.
- Friend Functions and Classes Learn C++ friend functions and friend classes - granting private access, friends for operators, hidden friends, tightly coupled classes, and when friendship is a design smell.
- Operator Overloading Learn C++ operator overloading - arithmetic and compound assignment, defaulted == and <=>, stream << and >>, subscript and call operators, member vs free functions, and good taste.
- Copy Constructors and Copy Assignment Learn C++ copy semantics - when objects are copied, memberwise copies, shallow vs deep copy with a resource-owning class, self-assignment, copy elision and copy-and-swap.
- Move Semantics Learn C++ move semantics - lvalues and rvalues, rvalue references, std::move, move constructors and assignment, noexcept moves in std::vector, and moved-from objects.
- The Rule of Zero, Three and Five Learn the C++ rules of zero, three and five - the six special member functions, when the compiler generates them, = default and = delete, and why the rule of zero wins.
- Inheritance Learn C++ inheritance - base and derived classes, constructor and destructor order, protected members, inheriting constructors, name hiding vs overriding, and final.
- Access in Inheritance, Multiple and Virtual Inheritance Learn C++ public, protected and private inheritance, multiple inheritance, the diamond problem, virtual inheritance and mixins, with runnable examples.
- Virtual Functions and Polymorphism Learn C++ virtual functions - dynamic dispatch, override and final, how vtables work, why base classes need virtual destructors, and how object slicing happens.
- Abstract Classes and Interfaces Learn C++ abstract classes - pure virtual functions, interfaces as abstract classes, programming to an interface, and factory functions that return unique_ptr<Base>.
- RTTI, dynamic_cast and typeid Learn C++ RTTI - dynamic_cast with pointers and references, cross casts, typeid and type_info, the four C++ casts compared, and when type checks are a design smell.
- Structs, Aggregates and Unions Learn C++ structs and aggregates - aggregate and designated initialization (C++20), structured bindings, unions and why std::variant is safer, and bit-fields.
- Enumerations: enum and enum class Learn C++ enumerations - unscoped enum vs scoped enum class, underlying types, std::to_underlying, enums in switch, converting to strings, and type-safe enum flags.
- Nested and Local Classes Learn C++ nested classes and their access rules, private helper types like list nodes, the pimpl idiom for stable headers, and local classes defined inside functions.
- PIMPL and API/ABI Stability Learn the PIMPL idiom in C++ to hide private members, cut compile times and keep a library's binary interface stable. Covers unique_ptr pimpl, copying, ABI rules and C handles.
Templates and Generic Programming
- Function Templates Learn C++ function templates - template syntax, template argument deduction, explicit template arguments, abbreviated templates with auto (C++20), and why templates live in headers.
- Class Templates Learn C++ class templates - build a generic Stack<T>, define members outside the class, use class template argument deduction and non-type parameters.
- Template Specialization Learn C++ template specialization - full and partial specialization of class templates, specializing function templates, and when overloading is the better choice.
- Concepts and Constraints Learn C++20 concepts - requires clauses, standard concepts like std::integral and std::ranges::range, writing your own concepts, and much clearer template errors.
- Variadic Templates and Fold Expressions Learn C++ variadic templates - parameter packs, pack expansion, fold expressions, a type-safe print and sum, forwarding references and perfect forwarding with std::forward.
- Compile-Time Programming: constexpr and consteval Learn C++ compile-time programming - constexpr functions, if constexpr, consteval and if consteval, static_assert, and building lookup tables while your code compiles.
- Type Traits and Metaprogramming Learn C++ type traits and metaprogramming - is_integral, remove_reference, conditional, writing your own traits, SFINAE with enable_if versus concepts, and std::declval.
- SFINAE and Overload Resolution Learn how C++ picks between overloads and templates, what substitution failure is not an error means, and how enable_if, void_t, decltype and priority tags select code at compile time.
The Standard Library (STL)
- The Standard Template Library Get the big picture of the C++ Standard Template Library - containers, iterators and algorithms, how they fit together, choosing the right container, and Big-O guarantees.
- Iterators Learn C++ iterators - begin and end, iterator categories, const and reverse iterators, insert iterators, iterator invalidation rules, and std::advance, next and distance.
- std::vector in Depth How std::vector really works - geometric growth and amortized cost, reserve and shrink_to_fit, emplace_back vs push_back, erase-remove, std::erase and vector<bool>.
- std::deque, std::list and std::forward_list Learn C++ std::deque, std::list and std::forward_list - how they store elements, O(1) operations, splice, iterator stability and the real cost of node-based containers.
- Container Adapters: stack, queue and priority_queue Learn C++ std::stack, std::queue and std::priority_queue - LIFO and FIFO operations, min-heaps with std::greater, custom comparators and top-k problems.
- std::map and std::multimap Learn C++ std::map and std::multimap - sorted key-value storage, insert vs operator[], try_emplace, find and contains, lower_bound range queries and custom ordering.
- std::unordered_map Learn C++ std::unordered_map - how hash tables give average O(1) lookups, buckets and load factor, reserve and rehash, custom hash functions and counting words.
- std::set and std::unordered_set Learn C++ std::set, std::multiset and std::unordered_set - unique elements, ordered vs hashed sets, custom ordering, removing duplicates and set operations with algorithms.
- std::pair and std::tuple Learn C++ std::pair and std::tuple - creating them, structured bindings, std::get, std::tie and std::ignore, std::apply, comparisons, and when a named struct is clearer.
- std::optional, std::variant, std::any and std::expected Learn the C++ vocabulary types - std::optional with value_or and and_then, std::variant with std::visit, std::any, and std::expected for error handling in C++23.
- std::bitset Learn C++ std::bitset - fixed-size bit sets, set, reset, flip and test, count, any, all and none, bitwise operators, to_string and to_ulong, plus real use cases.
- Lambda Expressions Learn C++ lambdas - syntax, capturing by value, by reference, this and init captures, mutable, generic and template lambdas, lambdas with algorithms, and recursion.
- Function Objects and std::function Learn C++ function objects - writing functors, std::less and std::greater, transparent comparators, std::function vs templates, std::invoke, bind_front and not_fn.
- Algorithms: Searching, Sorting and Counting Learn C++ STL algorithms for sorting and searching - sort, stable_sort, partial_sort, nth_element, find_if, binary_search, lower_bound, count_if, min_element, any_of.
- Algorithms: Transforming and Modifying Learn C++ modifying algorithms - copy and copy_if, transform, fill and generate, replace, the remove-erase idiom, unique, reverse, rotate, shuffle and sample.
- Numeric Algorithms Learn the C++ numeric algorithms - accumulate and its init-type trap, fold_left, reduce, inner_product, transform_reduce, partial_sum, scans, iota, gcd and lcm.
- Ranges and Views Learn C++20/23 ranges - range algorithms with projections, lazy views like filter, transform, take, split, zip, enumerate and chunk, pipelines with |, and std::ranges::to.
- multiset and multimap Families Learn C++ containers that allow duplicate keys - multimap, multiset, unordered_multimap and unordered_multiset - with equal_range, safe erasing, grouping and when to choose them.
Errors and Debugging
- Exceptions Learn C++ exceptions - throw, try and catch, catching by const reference, the standard exception hierarchy in stdexcept, stack unwinding with destructors, and rethrowing.
- Custom Exception Classes Learn to write custom exception classes in C++ - deriving from std::runtime_error, adding data, overriding what(), building hierarchies and nesting exceptions.
- Exception Safety and noexcept Learn C++ exception safety - the basic, strong and nothrow guarantees, RAII as the foundation, copy-and-swap, noexcept and move_if_noexcept, and why destructors must not throw.
- Error Handling Without Exceptions Handle errors in C++ without exceptions - return codes, [[nodiscard]], std::optional, std::expected with and_then and transform, std::error_code, and how to choose.
- Signal Handling Handle signals in C++ with <csignal> - std::signal and std::raise, what a handler may safely do, sig_atomic_t and atomic flags, graceful shutdown and threads.
- Assertions and Debugging Find C++ bugs fast - assert and NDEBUG, static_assert, debug logging with std::source_location, library assertions, sanitizers, gdb basics and reading template errors.
- Sanitizers and Valgrind Find memory errors, undefined behavior, data races and leaks in C++ with AddressSanitizer, UBSan, ThreadSanitizer and Valgrind - flags, sample reports and how to read them.
- Unit Testing with GoogleTest and Catch2 Learn C++ unit testing - test cases, assertions, fixtures, parameterized tests and matchers in GoogleTest and Catch2, plus CMake setup and a tiny runnable test harness of your own.
- clang-tidy and Static Analysis Catch C++ bugs before running the program. Turn on compiler warnings, configure clang-tidy checks, read its diagnostics, fix typical findings and run analysis in CI.
- Secure C++ Coding Write safer C++ by avoiding dangling references, check bounds with at() and span, validate integer sizes, enable hardened library modes and compiler hardening flags.
Input/Output and Files
- I/O Streams in Depth Master C++ I/O streams - the iostream class hierarchy, cin, cout, cerr and clog, fail/eof/bad state flags, recovering from bad input, manipulators and fast I/O.
- Reading and Writing Text Files Read and write text files in C++ with ifstream, ofstream and fstream - open modes, checking for errors, reading line by line or word by word, and RAII closing.
- Binary Files Work with binary files in C++ - write and read raw bytes, fixed-size records, seekg/tellg random access, padding pitfalls, endianness and std::byteswap (C++23).
- String Streams Use C++ string streams - parse text with istringstream, build strings with ostringstream, split strings with getline, reuse streams safely, and when std::format is better.
- The Filesystem Library Learn C++ std::filesystem - build and split paths, check files, create directories, list folders recursively, copy, rename and remove files, and handle errors safely.
Utilities
- Dates, Times and Durations with chrono Learn C++ std::chrono - durations and literals like 500ms, steady and system clocks, timing code, calendar dates with year_month_day, time zones, formatting and parsing.
- Random Numbers Learn to generate random numbers in modern C++ with <random> - why rand() is bad, mt19937 engines, seeding, uniform and normal distributions, weighted picks and std::shuffle.
- Regular Expressions Learn C++ regular expressions with std::regex - regex_match vs regex_search, capture groups, iterating over matches, regex_replace, splitting text, and performance traps.
- Numeric Limits, Complex Numbers and Bit Manipulation Query type limits with std::numeric_limits, compute with std::complex, use the C++20 <bit> functions popcount, bit_width and rotl, and reinterpret bits safely with std::bit_cast.
- Network Programming Basics Learn C++ network programming with POSIX sockets - a RAII socket wrapper, a TCP echo server and client on loopback, reliable send and receive loops, and message framing.
Concurrency
- Threads Learn C++ threads - start work with std::thread, join and detach, pass arguments safely, split work across cores, and stop std::jthread workers cleanly with stop tokens.
- Mutexes and Locks Learn to protect shared data in C++ - data races, std::mutex, lock_guard, unique_lock, scoped_lock for deadlock-free locking, shared_mutex for readers, and call_once.
- Race Conditions and Data Races Understand the difference between data races and race conditions in C++, see check-then-act, split-invariant and lazy-init bugs reproduced on demand, and fix them with locks, CAS and call_once.
- Condition Variables Learn std::condition_variable in C++ - wait with a predicate, notify_one and notify_all, spurious and lost wakeups, a producer-consumer queue, timeouts and stop tokens.
- Semaphores, Deadlocks and Classic Concurrency Problems Learn C++20 counting and binary semaphores, how they differ from mutexes, the four deadlock conditions, the dining philosophers, a bounded buffer and false sharing.
- Atomics and the Memory Model Learn C++ atomics - std::atomic, fetch_add, compare_exchange loops, memory orders like acquire and release, an atomic_flag spinlock, and when a mutex is the better choice.
- std::async, Futures and Promises Learn C++ task-based concurrency - std::async and launch policies, std::future and shared_future, promise, packaged_task, timeouts, and passing exceptions between threads.
- Coroutines Learn C++20 coroutines - lazy sequences with co_yield and std::generator (C++23), how co_await and co_return work, writing a minimal generator, and lifetime pitfalls.
- Parallel Algorithms and Execution Policies Speed up STL algorithms with C++17 execution policies - seq, par, par_unseq and unseq, parallel reduce and transform_reduce, and the rules for safe callbacks.
Modern C++ and Beyond
- Modern C++ Features by Standard A tour of what each C++ standard added, from C++11 lambdas and smart pointers to C++23 std::print and std::expected, with runnable examples and a C++26 preview.
- User-Defined Literals Learn C++ user-defined literals - write operator"" suffixes for units and types, raw and template forms, naming rules, and use std::literals such as s, sv, ms and i.
- C++20 Modules Learn C++20 modules - why headers are slow and leaky, export module and import, implementation units, partitions, import std in C++23, and how to build modules today.
- Build Systems: Make and CMake Learn how C++ projects are built - incremental builds, writing a Makefile, modern CMake with targets and build types, and managing libraries with vcpkg and Conan.
- Compilers, Flags and Optimization Learn the C++ compiler flags that matter - warning sets, -O levels, debug info, sanitizers, LTO and hardening - and see how the optimizer transforms code, with live demos.
- Writing Fast C++ Learn to write fast C++ - measure with chrono, cache-friendly data layouts, vector versus list, avoiding copies and allocations, reserve, move, small string optimization and inlining.
- Design Patterns in C++ Learn the design patterns that matter in modern C++ - RAII, factory, builder, strategy, observer, CRTP, PIMPL and singleton - with runnable examples and their trade-offs.
- Best Practices and Common Mistakes The habits that keep modern C++ correct and readable - clear ownership, const correctness, no raw new, initialized variables, algorithms, warnings - and the bugs to avoid.
- C and C++: Differences and Interoperability How C and C++ differ - what C++ added, valid C that C++ rejects, printf vs std::print, malloc vs new - and how to call C libraries with extern "C" safely.
- Allocators and std::pmr Learn C++ allocators and std::pmr - write a minimal custom allocator, use monotonic buffer and pool resources, pmr containers, allocator propagation and when it pays off.
- std::bit_cast, mdspan and Newer Utilities A tour of useful C++20 and C++23 library additions - std::bit_cast, bit utilities, byteswap, to_underlying, flat_map, move_only_function and mdspan for multidimensional views.
- Cache-Friendly Code Learn why memory layout often matters more than instructions. Understand CPU caches and cache lines, spatial and temporal locality, array of structs versus struct of arrays, and hot/cold splitting.
Projects
- Project: Grade Book Build a C++ grade book in four stages. Parse names and scores from input, reject bad lines with std::expected, compute statistics and print a neat report.
- Project: Bank Account System Build a C++ bank account system in four stages - an encapsulated Account class, custom exceptions, a transaction history, polymorphic accounts and a command processor.
- Project: Library Catalog Build a C++ library catalog in four stages - store books in a std::map, parse commands from input, search and sort with ranges, and manage loans with clear rules.
- Project: Text Statistics Build a C++ text analyzer in four stages - count words, lines and sentences, find the most frequent and longest words with unordered_map, and print a sorted report.
- Project: Tic-Tac-Toe Build tic-tac-toe in C++ in four stages - a std::array board, enum class marks, validated moves from input, win detection and an unbeatable minimax computer player.
- Project: A Small Matrix Library Build a C++ Matrix class template in four stages - vector storage, operator overloading, size-checking exceptions, assert-based tests, a concept and a std::formatter.
Data Structures and Algorithms
- Data Structures in C++ Build classic data structures in modern C++ - a growable array, a stack, a ring-buffer queue, a linked list with unique_ptr nodes and a binary search tree.
- Searching and Sorting Algorithms Implement linear and binary search plus bubble, selection, insertion, merge, quick and heap sort in C++, with traces, Big-O analysis and timings against std::sort.
- Graphs, Recursion and Backtracking Represent graphs in C++ with adjacency lists, explore them with BFS and DFS, find shortest paths with Dijkstra, order tasks topologically and solve N-Queens by backtracking.
Practice and Review
- C++ Cheat Sheet A one-page modern C++ cheat sheet with types, strings, format specs, control flow, functions, lambdas, smart pointers, classes, templates, STL containers and ranges.
- C++ Programs: 40 Classic Examples 40 classic C++ programs with output: prime check, factorial, Fibonacci, palindromes, GCD and LCM, Armstrong numbers, base conversion, sorting, matrices and more.
- C++ Programs: Pattern Printing C++ pattern printing programs with output: half and inverted pyramids, hollow shapes, diamond, hollow diamond, Floyd's triangle and number and letter patterns.
- C++ Programs: Matrix Problems C++ matrix programs with output: trace, normal, rotate 90 degrees, spiral order, boundary sum, symmetry checks, row swap, determinant and 2D prefix sums.
- C++ Programs: Array and Searching Puzzles C++ array puzzles with output: common elements, prefix sums, Dutch flag sort, wave sort, rotated array search, sorting 2D rows and next greater element.
- C++ Programs: String Tasks C++ string programs with output: add binary strings, strip leading zeros, split a string, pangram check, reverse with a stack and word initials.
- C++ Programs: OOP and STL Recipes C++ class and STL recipes with output: singleton, interface, complex class with ++ and --, vector of pairs to map, merging maps, multiset, permutations.
- C++ Programs: Files and Dates C++ file and date programs with output: temp file, rename, copy, append, list a folder, print a month calendar and convert local time to UTC.
- C++ Practice Exercises 29 graded C++ exercises with solutions on loops, functions, strings, vectors, maps, classes, templates, the STL and threads. Write and run C++ in your browser.
- C++ Interview Questions 50 common C++ interview questions with clear answers, from pointers, references and const to virtual functions, smart pointers, move semantics, the STL and threads.