C++ Quick Revision Notes

Exam-ready key points, definitions, and code takeaways across all 37 C++ modules.

Module 1: Introduction to C++

What is C++? History, Features & Standards (C++98 to C++23)

Understand what C++ is, Bjarne Stroustrup's design goals, key features, paradigms, and the evolution of Modern C++ from C++98 through C++23.

  • • **Procedural Programming**: Top-down functions, structs, and direct hardware/memory control.
  • • **Object-Oriented Programming (OOP)**: Encapsulation, inheritance, and runtime polymorphism (`virtual` tables).
  • • **Generic Programming**: Compile-time type parameterization using **Templates** and **C++20 Concepts**.
Read Full Lesson
Module 2: Environment Setup

C++ Compilers, IDEs & The 4-Stage Compilation Process

Learn how GCC/G++, Clang, and MSVC work, how to set up C++ on Windows/Linux/macOS, and how preprocessing, compilation, assembly, and linking produce an executable.

  • • **G++ (GNU C++)**: Standard on Linux and via MinGW-w64 / MSYS2 on Windows.
  • • **Clang (LLVM)**: Fast compilation, rich diagnostics, default on macOS.
  • • **MSVC**: Microsoft Visual C++ compiler bundled with Visual Studio on Windows.
Read Full Lesson
Module 3: C++ Program Structure

Anatomy of a C++ Program, Namespaces & Execution Flow

Break down every line of a C++ program: #include directives, iostream, main(), statements, expressions, comments, and the std namespace.

  • • **`#include <iostream>`**: Inserts standard input/output stream declarations during preprocessing.
  • • **Namespaces (`std`)**: Prevents symbol collisions across libraries.
  • • **`int main()`**: The mandatory entry point called by the OS runtime. Returning `0` indicates success; non-zero indicates an error code.
Read Full Lesson
Module 4: Tokens and Fundamentals

Tokens, Variables, Scope & Storage Duration

Master C++ tokens (keywords, identifiers, literals), variable initialization, local/global/static scope, and storage duration.

  • • **Copy Init**: `int x = 10;`
  • • **Direct Init**: `int x(10);`
  • • **Brace / Uniform Init (C++11)**: `int x{10};` — **Preferred**, because it prevents narrowing data loss (`int x{3.14};` fails to compile!).
Read Full Lesson
Module 4: Tokens and Fundamentals

Data Types, Type Modifiers, sizeof, Casting & auto/decltype

Explore fundamental C++ data types, signed/unsigned/short/long modifiers, sizeof operator, implicit/explicit casting, auto, and decltype.

  • • Explore fundamental C++ data types, signed/unsigned/short/long modifiers, sizeof operator, implicit/explicit casting, auto, and decltype.
  • • Practice writing and running standard examples.
  • • Apply best practices and debugging techniques.
Read Full Lesson
Module 5: Operators

C++ Operators, Bitwise Operations, Precedence & Pitfalls

Comprehensive guide to arithmetic, relational, logical, bitwise, shift, ternary, and comma operators, plus precedence and common mistakes.

  • • **Arithmetic**: `+`, `-`, `*`, `/`, `%` (integers only).
  • • **Relational & Logical**: `<`, `>`, `==`, `!=`, `&&`, `||`, `!` (short-circuit evaluation).
  • • **Bitwise & Shift**: `&` (AND), `|` (OR), `^` (XOR), `~` (NOT), `<<` (left shift, ×2), `>>` (right shift, ÷2).
Read Full Lesson
Module 6: Input and Output

C++ Streams (cout, cin, cerr, clog), getline() & iomanip Formatting

Master standard I/O streams, reading full lines with getline(), formatting numbers with <iomanip>, and clearing input buffer errors.

  • • **`std::cout`**: Buffered standard output (`<<` insertion).
  • • **`std::cin`**: Standard input (`>>` extraction).
  • • **`std::cerr`**: Unbuffered standard error (flushes immediately—ideal for critical errors).
Read Full Lesson
Module 7: Control Statements

Decision Making: if-else, switch & Enum Switching

Write clean conditional logic using if, if-else, else-if ladders, switch statements, C++17 init-statements, and enum class.

  • • **`if / else if / else`**: Evaluates boolean expressions sequentially.
  • • **C++17 Init-Statement**: `if (auto val = compute(); val > 0) { ... }` keeps `val` scoped strictly to the conditional.
  • • **`switch`**: Branches on integral or `enum` values using compiler jump tables (often O(1)). Always include `break;` unless using C++17 `[[fallthrough]];`.
Read Full Lesson
Module 7: Control Statements

Loops in C++: for, while, do-while, Range-Based for & Jump Statements

Master iteration with for, while, do-while, C++11 range-based for loops, nested loops, break, continue, and avoiding infinite loop bugs.

  • • **`for`**: Known iteration count (`for (int i = 0; i < n; ++i)`).
  • • **`while`**: Entry-controlled; runs 0 or more times.
  • • **`do-while`**: Exit-controlled; guaranteed at least 1 execution (ideal for menus).
Read Full Lesson
Module 8: Functions

Functions, Parameter Passing, Overloading & Inline/Constexpr

Learn function declarations vs definitions, pass-by-value vs reference vs pointer, default arguments, overloading rules, inline, constexpr, and noexcept.

  • • **Pass by Value**: Copies argument; safe for small primitives (`int`, `double`).
  • • **Pass by `const` Reference (`const T&`)**: Zero-copy read-only access—default choice for `std::string`, `std::vector`, and classes.
Read Full Lesson
Module 8: Functions

Recursion, Function Pointers & Callbacks

Understand direct/indirect recursion, call stack frames, tail recursion concepts, function pointers, and callback patterns.

  • • **Direct vs. Indirect Recursion**: Function A calls A vs. A calls B which calls A.
  • • **Tail Recursion**: Recursive call is the very last operation; modern compilers with `-O2` can optimize it into a loop (Tail Call Optimization).
Read Full Lesson
Module 9: Arrays

1D & 2D Arrays, Memory Layout & Array Algorithms

Understand contiguous array memory layout, 1D/2D arrays, array decay when passing to functions, reversal, rotation, and std::array.

  • • random access via `*(arr + i)`. 2D arrays `int mat[R][C]` are stored in **row-major order** in memory (row 0 followed by row 1), making row-wise traversal cache-friendly.
  • • it to `int*`, losing its size. Prefer `std::array<int, N>` (fixed size, knows `.size()`, supports `.at()` bounds checking) or `std::vector<int>` (dynamic size).
Read Full Lesson
Module 10: Strings

C-Style Strings vs std::string & Essential String Methods

Compare null-terminated char arrays (<cstring>) with modern std::string, and master substr(), find(), replace(), insert(), erase(), and conversions.

  • • **C-Style Strings**: Null-terminated `char` arrays (`'\0'`). Functions in `<cstring>` (`strlen`, `strcpy`, `strncpy`, `strcat`, `strcmp`) require manual buffer management and risk buffer overflows.
  • • **`std::string` (`<string>`)**: Dynamic, RAII-managed string class supporting `+`, `==`, `.length()`, `.substr()`, `.find()`, `.replace()`, `.insert()`, `.erase()`, and `std::to_string()`.
  • • **Mistake**: Comparing `find()` with `>= 0` (since `find()` returns `size_t`, an unsigned type!). Always compare with `std::string::npos`.
Read Full Lesson
Module 11: Pointers

Pointers, Memory Addresses, nullptr, Pointer Arithmetic & Const Pointers

Deep dive into memory addresses, & and * operators, nullptr, pointer arithmetic, pointer-to-pointer, void*, const pointers, and avoiding dangling/wild pointers.

  • • **`nullptr` (C++11)**: Type-safe null pointer literal (`std::nullptr_t`), eliminating `NULL` (0) overload ambiguity.
  • • **Wild Pointer**: Uninitialized pointer -> initialize to `nullptr`.
  • • **Dangling Pointer**: Points to freed/out-of-scope memory -> set to `nullptr` after `delete`.
Read Full Lesson
Module 12: References

Lvalue & Rvalue References, Const References & Pointers vs References

Master C++ references, why references cannot be null or reseated, const T& optimization, and C++11 rvalue references (T&&) for move semantics.

  • • is an alias for an existing object. Unlike pointers, references **must be initialized at declaration**, **cannot be null**, and **cannot be reseated**.
  • • `const T&` can bind to both lvalues and temporary rvalues, extending a temporary's lifetime to the reference's scope!
  • • binds exclusively to temporary/expiring values, enabling **move constructors** and **move assignment** to steal heap buffers in O(1) instead of deep-copying.
Read Full Lesson
Module 13: Dynamic Memory Management

Stack vs Heap, new/delete, RAII & Smart Pointers (unique_ptr, shared_ptr, weak_ptr)

Master heap allocation with new/delete, prevent memory leaks and double deletion with RAII, and use C++11 smart pointers properly.

  • • **Stack**: Automatic, fast LIFO allocation; bounded size.
  • • **Heap**: Dynamic runtime allocation; persists until explicitly freed. Always pair `new` with `delete` and `new[]` with `delete[]`.
  • • **Memory Leak**: Forgetting `delete` or throwing an exception before `delete`.
Read Full Lesson
Module 14: Object-Oriented Programming

Classes, Objects, Encapsulation, Constructors & Destructors

Build well-encapsulated C++ classes with public/private/protected access specifiers, default/parameterized/copy/move constructors, initializer lists, and destructors.

  • • **Member Initializer List**: `User(std::string n) : name(std::move(n)) {}` initializes members directly (required for `const` and reference members).
  • • **Delegating Constructors (C++11)**: One constructor forwards to another.
  • • **Copy / Move Constructors & Destructor**: If a class manages a raw resource, follow the **Rule of 5** (Destructor, Copy Ctor, Copy Assign, Move Ctor, Move Assign). Better yet, use smart pointers/STL and follow the **Rule of 0**!
Read Full Lesson
Module 15: Inheritance

Inheritance Types, Constructor Order & The Diamond Problem

Learn single, multiple, multilevel, and hierarchical inheritance, public/protected/private modes, constructor/destructor order, and virtual inheritance.

  • • **`public` inheritance ("is-a")**: Public stays public; protected stays protected.
  • • **`protected` / `private` inheritance**: Models "implemented-in-terms-of" (composition is usually cleaner!).
  • • **Construction**: Base -> Member objects -> Derived.
Read Full Lesson
Module 16: Polymorphism

Virtual Functions, Abstract Classes, vtable Internals & Virtual Destructors

Master runtime polymorphism with virtual functions, override, final, pure virtual interfaces, vptr/vtable internals, virtual destructors, and dynamic_cast.

  • • **Compile-Time**: Function overloading, operator overloading, templates.
  • • **Runtime**: Virtual functions dispatched through base pointers/references.
  • • **Pure Virtual (`= 0`)**: Makes the class **abstract** (cannot be instantiated).
Read Full Lesson
Module 17: Operator Overloading

Operator Overloading Rules, Arithmetic & Stream (<< / >>) Operators

Learn which operators can be overloaded, member vs friend non-member overloads, overloading +, ==, ++, and << / >> stream operators.

  • • **Cannot Overload**: `::`, `.`, `.*`, `?:`, `sizeof`, `typeid`.
  • • **Member vs. Friend Non-Member**: Binary operators like `+` or `==` are often non-members for symmetry; `<<` and `>>` **must** be non-member `friend` functions because the left operand is `std::ostream&` / `std::istream&`.
Read Full Lesson
Module 18: Structures, Unions, and Enumerations

Structs, Unions & Scoped Enumerations (enum class)

Compare struct vs class in C++, understand union shared memory layout, and prefer type-safe C++11 enum class over unscoped enums.

  • • for type-safe tagged unions.
  • • for strong type safety.
Read Full Lesson
Module 19: Namespaces and Modular Programming

Namespaces, Header Guards & Multi-File Modular Design

Organize large C++ codebases using nested and anonymous namespaces, header guards (#ifndef / #pragma once), and separation of declarations (.hpp) from definitions (.cpp).

  • • **Nested Namespaces (C++17)**: `namespace codezov::engine { ... }`.
  • • **Namespace Alias**: `namespace ce = codezov::engine;`.
  • • **Anonymous Namespace**: `namespace { void helper() {} }` gives internal linkage (private to the current `.cpp` translation unit—replacing C-style `static` free functions).
Read Full Lesson
Module 20: Exception Handling

Exception Handling: try/catch/throw, Stack Unwinding & Custom Exceptions

Handle runtime errors cleanly with try/catch/throw, std::exception subclasses, stack unwinding with RAII, and noexcept guarantees.

  • • **Basic**: No leaks, invariants preserved.
  • • **Strong**: Commit-or-rollback semantics.
  • • **Nothrow (`noexcept`)**: Guaranteed never to throw (critical for destructors and move constructors!).
Read Full Lesson
Module 21: Templates and Generic Programming

Function & Class Templates, Specialization, Variadic Templates & C++20 Concepts

Write reusable, zero-overhead generic code with function and class templates, template specialization, variadic templates, and C++20 Concepts.

  • • **Full & Partial Specialization**: Customize template behavior for specific types (e.g., pointers `T*`).
  • • **Non-Type Template Parameters**: `template <typename T, std::size_t N>` (like `std::array`).
Read Full Lesson
Module 22: STL – Standard Template Library

STL Sequence Containers & Adaptors (vector, array, deque, stack, queue, priority_queue)

Master STL architecture, std::vector, std::array, std::deque, std::list, and adaptors (stack, queue, priority_queue) with time complexities.

  • • | Contiguous dynamic array | O(1) | O(1) amortized | O(n) |
  • • | Fixed stack array | O(1) | N/A | N/A |
  • • | Chunked blocks | O(1) | O(1) | O(1) |
Read Full Lesson
Module 22: STL – Standard Template Library

Associative & Unordered Containers (set, map, unordered_map) & STL Algorithms

Compare O(log n) ordered map/set vs O(1) avg unordered_map/unordered_set, and use sort, binary_search, lower_bound, accumulate, and pair/tuple.

  • • **Utilities**: `std::pair`, `std::tuple`, and C++17 structured bindings `auto [k, v] = ...`.
Read Full Lesson
Module 23: File Handling

File Streams (ifstream, ofstream, fstream), Binary Files & File Pointers

Read, write, and append text and binary files safely using <fstream>, RAII file closing, file modes, and seekg/tellg positioning.

  • • **Modes**: `std::ios::in`, `std::ios::out`, `std::ios::app` (append), `std::ios::binary`.
Read Full Lesson
Module 24: Preprocessor and Macros

C++ Preprocessor Directives, Conditional Compilation & Macro Pitfalls

Understand #define object/function macros, conditional compilation (#ifdef, #ifndef, #if), predefined macros (__LINE__, __FILE__), and why constexpr/inline beat macros.

  • • Understand #define object/function macros, conditional compilation (#ifdef, #ifndef, #if), predefined macros (__LINE__, __FILE__), and why constexpr/inline beat macros.
  • • Practice writing and running standard examples.
  • • Apply best practices and debugging techniques.
Read Full Lesson
Module 25: Type System and Advanced Language Features

constexpr, consteval, Value Categories (lvalue/rvalue), Move Semantics & Perfect Forwarding

Master compile-time evaluation (constexpr, consteval, static_assert), type_traits, lvalues/xvalues/prvalues, std::move, and std::forward.

  • • **`constexpr`**: Can evaluate at compile time or runtime.
  • • **`consteval`**: *Must* evaluate at compile time (immediate function).
  • • **`constinit`**: Guarantees compile-time static initialization (no static initialization order fiasco).
Read Full Lesson
Module 26: Lambda Expressions and Functional Programming

Lambda Expressions & Functional Programming in Modern C++

Complete Advanced guide to C++ Lambdas: syntax breakdown, capture lists, closure internals, mutable & generic lambdas, STL algorithms, callbacks, std::function, constexpr, Concepts, and best practices.

  • • **Why `auto` is used**: Every lambda expression has a **unique, unnamed closure type** generated by the compiler. You cannot write its type name explicitly, so `auto` deduces it at compile time with zero overhead.
  • • **Why it can be stored in a variable**: The lambda evaluates to a temporary **closure object** (an instance of that unnamed class), which `square` stores by value.
  • • **How it is invoked**: `square(5)` calls `operator()(5)` on the closure object, identical to a normal function call.
Read Full Lesson
Module 27: Multithreading and Concurrency

std::thread, Mutex Synchronization, Atomics & std::async

Build thread-safe concurrent C++ programs using std::thread, mutex, lock_guard, scoped_lock, condition_variable, std::atomic, and std::async.

  • • **Race Condition**: Unsynchronized concurrent read/write on shared mutable state -> Undefined Behavior.
  • • **`std::lock_guard<std::mutex>`**: Simple RAII lock for a single mutex.
  • • **`std::unique_lock<std::mutex>`**: Flexible lock supporting deferred locking and `std::condition_variable`.
Read Full Lesson
Module 28: C++ Date and Time

C++ <chrono> Library: Clocks, Durations & Benchmarking

Measure elapsed time accurately with std::chrono::steady_clock, durations, time_points, and format calendar dates with <ctime> / strftime.

  • • **`std::chrono::steady_clock`**: Monotonic clock (never adjusts backward)—use for **benchmarking** and timeouts.
  • • **`std::chrono::system_clock`**: Wall-clock calendar time; converts to `std::time_t` for formatting with `std::localtime` / `std::strftime`.
  • • **`std::chrono::high_resolution_clock`**: Shortest tick period available.
Read Full Lesson
Module 29: C++ Math and Algorithms

<cmath> Functions & Modern <random> Number Generation

Use <cmath> (pow, sqrt, abs, trig, log) and replace C's rand() with <random> Mersenne Twister (std::mt19937) and uniform/normal distributions.

  • • (`std::mt19937`, seeded via `std::random_device`) from **Distributions** (`std::uniform_int_distribution`, `std::normal_distribution`).
Read Full Lesson
Module 30: Modern C++ Features

Modern C++17, C++20 & C++23 Features Compared to Legacy C++

Master std::optional, std::variant, std::any, if constexpr, C++20 Concepts, Ranges, std::span, <=>, and C++23 std::expected.

  • • **`std::optional<T>`**: Stack-allocated nullable value (no heap, no magic `-1`).
  • • **`std::variant<Ts...>`**: Type-safe discriminated union.
  • • **`std::any`**: Type-safe container for any copyable type.
Read Full Lesson
Module 31: Data Structures Using C++

Linear & Non-Linear Data Structures: Linked Lists, Trees, Graphs (BFS/DFS) & Sorting

Implement and analyze Time/Space Complexity (Big O) for Linked Lists, Stacks, Queues, Binary Search Trees, Graphs (BFS/DFS), and Merge/Quick Sort.

  • • **Binary Trees & BST**: O(h) search/insert (O(log n) when balanced like AVL / Red-Black).
  • • **Graphs**: Adjacency List (`vector<vector<int>>`), **BFS** (shortest unweighted path via `queue`), **DFS** (cycle detection/topological sort via recursion/`stack`).
Read Full Lesson
Module 32: C++ for Competitive Programming

Competitive Programming: Fast I/O, Two Pointers, Prefix Sums, DP & DSU

Accelerate competitive programming with ios::sync_with_stdio(false), prefix sums, two pointers, sliding window, bit tricks, DP, and Disjoint Set Union.

  • • **Prefix Sums & Difference Arrays**: O(1) range sums.
  • • **Two Pointers & Sliding Window**: Reduce O(n²) to O(n).
  • • **Binary Search on Answer**: Monotonic predicate search.
Read Full Lesson
Module 33: Design Patterns in C++

Essential Design Patterns in Modern C++ (Singleton, Factory, Strategy, Observer)

Implement thread-safe Meyers' Singleton, Factory Method, Builder, Strategy, and Observer patterns idiomatically in Modern C++.

  • • **Meyers' Singleton**: Function-local `static` instance (thread-safe since C++11).
  • • **Factory & Abstract Factory**: Return `std::unique_ptr<Base>` to decouple creation.
  • • **Builder**: Fluent method chaining for complex configs.
Read Full Lesson
Module 34: Software Engineering with C++

Clean C++ Architecture, Unit Testing, Assertions & Performance Profiling

Structure production C++ repositories, apply SOLID & Core Guidelines, write unit tests, use <cassert> / static_assert, and profile bottlenecks.

  • • principles, **C++ Core Guidelines**, and write automated unit tests (GoogleTest / Catch2) using TDD.
Read Full Lesson
Module 35: Build Systems and Development Tools

CMake, Makefiles, GDB Debugging & AddressSanitizer (ASan/UBSan)

Automate builds with Make and modern CMakeLists.txt, debug with GDB/LLDB, and catch memory bugs using -fsanitize=address,undefined.

  • • generates native build files (Ninja, Make, Visual Studio) from `CMakeLists.txt`. Link static (`.a`) or shared (`.so`/`.dll`) targets cleanly with `target_link_libraries`.
  • • Compile with `-g` for debug symbols; inspect backtraces (`bt`) and breakpoints in **GDB/LLDB**.
  • • Enable **AddressSanitizer & UBSan** in CI/testing: `g++ -g -O1 -fsanitize=address,undefined main.cpp` to catch buffer overflows, use-after-free, and signed overflow immediately!
Read Full Lesson
Module 36: C++ Security and Best Practices

Secure C++ Coding: Avoiding Undefined Behavior, Buffer Overflows & Integer Overflows

Eliminate security vulnerabilities in C++ by preventing buffer overflows, signed integer overflows, dangling pointers, and unvalidated inputs.

  • • Replace `gets`, `strcpy`, `sprintf` with `std::string`, `std::string_view`, and `std::format` / `snprintf`.
  • • Replace raw `new`/`delete` with `std::unique_ptr`, `std::vector`, and RAII.
  • • in C++ (the compiler may optimize away naive `x + 1 > x` checks!). Always check bounds *before* arithmetic, validate all external inputs, and compile with `-Wall -Wextra -Werror`.
Read Full Lesson
Module 37: C++ Applications and Projects

Capstone Project: OOP & STL-Powered Student Management System

Build a complete menu-driven Student Record Management System using C++ classes, std::vector, std::algorithm, and clean modular design.

  • • **Beginner**: Scientific Calculator, Number Guessing Game, Banking CLI.
  • • **Intermediate**: Student Management System, Library System, Expense Tracker, ATM Simulation.
  • • **Advanced**: In-Memory KV Store, Mini Shell, Multithreaded Downloader, Data Structures Visualizer.
Read Full Lesson