Course C++
C++ Cheatsheet
A quick, printable reference with essential modern C++ syntax: types, std::string, control flow, pass-by-reference, RAII classes, iostream, std::vector, and smart pointers. Print to PDF with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
0. Core C++ Invariants & Pitfalls to Avoid
Five habits that prevent undefined behavior (UB), memory leaks, and parser traps.
- Always initialize local primitive variables (int x = 0;): reading uninitialized stack memory is Undefined Behavior.
- Prefer std::vector, std::array, and smart pointers (std::unique_ptr) over manual new/delete or raw C arrays.
- Pass non-trivial objects by const reference (const std::string&) instead of copying on every call.
- Never forget the trailing semicolon (;) after a class { ... }; or struct { ... }; definition.
- Include break; (or [[fallthrough]];) in switch cases unless fallthrough is strictly intentional.
1. Variables & Basic Types
Declarations
int x = 42; // Integer double pi = 3.14159; // Floating point char grade = 'A'; // Single character (single quotes) bool isFun = true; // Boolean (true/false) const int MAX = 100; // Constant auto inferred = 5.5; // Automatic type deduction (double)Statements terminate with ; and auto deduces types directly from the initializer.
Pitfall: Declaring int n; without an initializer leaves garbage bytes in stack storage.
Standard Strings
#include <string> std::string name = "Alice"; std::string greet = "Hello " + name; std::size_t len = greet.length(); // or greet.size()Use double quotes for strings and single quotes ('A') for single characters.
Pitfall: Adding two raw string literals ("a" + "b") tries to add pointers and fails to compile: ensure at least one operand is std::string.
2. Control Flow
Conditionals (if / else)
if (score >= 90) { std::cout << "Excellent!"; } else if (score >= 60) { std::cout << "Passed"; } else { std::cout << "Failed"; }Conditions sit in parentheses followed by brace-delimited branches.
Pitfall: Accidentally writing if (x = 5) assigns 5 to x instead of testing equality with ==.
Loops (for / while)
// Classic for loop for (int i = 0; i < 5; ++i) { std::cout << i << " "; } // While loop while (count > 0) { count--; }Use for for bounded iterations and while for dynamic stopping conditions.
Pitfall: Using <= size() accesses one past the end of zero-indexed containers — the last valid index is size() - 1.
Switch statement
switch (op) { case '+': res = a + b; break; case '-': res = a - b; break; default: res = 0; }Dispatches integral or enum values directly to matching labels.
Pitfall: Omitting break; silently executes the body of the following case statement.
3. Functions & References
Basic definition
int sum(int a, int b) { return a + b; } void greet() { std::cout << "Hello!"; }void functions perform side effects without returning a value.
Pitfall: Falling off the end of a value-returning function without return triggers Undefined Behavior.
Pass by Reference (& and const&)
// Modifies caller variable directly void doubleIt(int& n) { n = n * 2; } // Pass by const reference (zero copy, read-only) void showName(const std::string& s) { std::cout << s; }Pass big values as const T& to avoid unnecessary copies.
Pitfall: Never return a reference or pointer to a local stack variable — it becomes a dangling reference as soon as the function returns.
4. Classes & OOP
Class declaration
class Rectangle { private: int width; int height; public: // Member initializer list Rectangle(int w, int h) : width(w), height(h) {} int getArea() const { return width * height; } };Members default to private in class; mark read-only methods const.
Pitfall: Missing the closing semicolon after }; confuses the compiler on subsequent declarations.
Object usage
Rectangle rect(5, 4); // Stack allocation (RAII) int area = rect.getArea(); // Method call -> 20Stack-allocated objects automatically run their destructors on scope exit.
Pitfall: Writing Rectangle r(); parses as a function prototype (Most Vexing Parse): use Rectangle r{}; or constructor arguments.
5. I/O Streams, Vectors & Smart Pointers
<iostream> Library
#include <iostream> std::cout << "Value: " << x << '\n'; std::cin >> x; std::cout << std::boolalpha << true;std::boolalpha prints true/false rather than 1/0; std::endl flushes after newline.
Pitfall: Calling std::endl inside tight loops flushes I/O buffers every iteration — prefer "\n".
std::vector & unique_ptr (RAII)
#include <vector> #include <memory> std::vector<int> nums = {1, 2, 3}; nums.push_back(4); for (int v : nums) { std::cout << v << ' '; } auto ptr = std::make_unique<int>(42); // auto-freed on scope exitStandard containers and smart pointers eliminate manual heap bookkeeping.
Pitfall: push_back can reallocate a vector’s backing buffer, invalidating existing pointers, references, and iterators into it.
6. Pointers, nullptr & RAII Smart Pointers
Address-of (&), Dereference (*) & nullptr
int value = 10; int* ptr = &value; if (ptr != nullptr) { *ptr = 25; } // value is now 25Always check ptr != nullptr before dereferencing with *ptr.
Pitfall: Dereferencing nullptr or the address of a destroyed stack local triggers Undefined Behavior.
unique_ptr, shared_ptr & weak_ptr
auto u = std::make_unique<int>(42); auto u2 = std::move(u); // ownership moved, u == nullptr auto s1 = std::make_shared<int>(99); std::weak_ptr<int> w = s1; if (auto locked = w.lock()) { std::cout << *locked; }Prefer std::make_unique and std::make_shared over manual new / delete.
Pitfall: Mutually referencing std::shared_ptr instances leak forever: break cycles with std::weak_ptr.
7. Inheritance, Virtual Polymorphism & Templates
Abstract Base, override & virtual Destructor
class Shape { public: virtual double area() const = 0; virtual ~Shape() = default; }; class Circle : public Shape { double r; public: explicit Circle(double r) : r(r) {} double area() const override { return 3.14159 * r * r; } };Mark overridden methods with override and give polymorphic bases virtual ~Base() = default;.
Pitfall: Deleting a derived object through Base* without a virtual destructor causes Undefined Behavior.
Generic Templates & Instantiation
template <typename T> class Box { T val; public: explicit Box(T v) : val(std::move(v)) {} const T& get() const { return val; } }; template <typename T> T clampMin(T v, T minVal) { return v < minVal ? minVal : v; }Templates instantiate at compile time with zero runtime dispatch overhead.
Pitfall: Splitting template definitions across .h and .cpp without explicit instantiation causes linker errors.
8. Move Semantics (&&), string_view & span
Rvalue Reference && & noexcept Move
class Buffer { int* data = nullptr; public: Buffer(Buffer&& other) noexcept : data(other.data) { other.data = nullptr; } };Mark move constructors noexcept so std::vector moves rather than copies during reallocation.
Pitfall: Never assume the value of an object after std::move(obj): only destroy or reassign it.
Non-Owning Views (std::string_view & std::span)
#include <string_view> #include <span> std::size_t countChars(std::string_view sv) { return sv.size(); } int firstOrZero(std::span<const int> items) { return items.empty() ? 0 : items.front(); }string_view and span bind cleanly to literals, stack arrays, and heap containers without copying.
Pitfall: Never return a std::string_view pointing into a local std::string created inside the function.
9. Lambdas, STL Algorithms & C++20 Ranges
Lambda Expressions & Capture Lists
int threshold = 10; int hits = 0; auto check = [threshold, &hits](int v) { if (v > threshold) ++hits; return v > threshold; };Capture by value [x] safely copies primitives; use [&x] only while the referenced variable stays in scope.
Pitfall: Capturing [&] in a lambda stored beyond the current stack frame (async callbacks/threads) creates dangling references.
<algorithm>, std::sort & std::views
#include <algorithm> #include <ranges> std::sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; }); auto evens = nums | std::views::filter([](int n) { return n % 2 == 0; });Standard algorithms and std::views compose cleanly without manual index errors or intermediate allocations.
Pitfall: std::views are lazy non-owning views: keep the underlying container alive longer than any view over it.
10. std::optional, RAII Exceptions & Concurrency
std::optional & Catching by const&
#include <optional> std::optional<int> findPort(bool ok) { return ok ? std::optional<int>{8080} : std::nullopt; } int p = findPort(false).value_or(80);Model expected missing values with std::optional and catch exceptions as const std::exception&.
Pitfall: Dereferencing an empty optional via *opt is UB; always check has_value() or use .value_or().
std::jthread & std::scoped_lock (deadlock-free)
#include <thread> #include <mutex> std::mutex mtx; int shared = 0; void addSafe(int delta) { std::scoped_lock lock(mtx); shared += delta; }scoped_lock acquires one or more mutexes with deadlock avoidance and unlocks automatically on scope exit.
Pitfall: Letting a raw std::thread go out of scope without .join() or .detach() calls std::terminate() and aborts.