C++ Notes Library
Short revision notes for the topics covered so far.
Compile and run
Source code must be compiled before it can run.
- Compiler: translates .cpp files to machine code.
- g++ -std=c++17 -Wall file.cpp -o app
- Recompile after every change.
g++ -std=c++17 -Wall main.cpp -o main
./mainThe main function
Execution starts at int main().
- Exactly one main per program.
- return 0 means success.
- Returning from main ends the program.
int main() {
// your code
return 0;
}Statements and blocks
Statements end with ; and blocks use { }.
- C++ is case-sensitive.
- Whitespace is mostly ignored, use it for readability.
- Every { needs a matching }.
Common mistake: Forgetting ; often produces an error on the following line.
Comments
Notes for humans, ignored by the compiler.
- // single line
- /* multi-line */
- Explain why, not what.
// single line
/* multiple
lines */Common mistake: /* */ comments cannot be nested.
The std namespace
Standard library names live inside std.
- Access with std::cout, std::string.
- using namespace std; is convenient but can cause clashes in larger code.
Printing with std::cout
Send values to the screen with <<.
- Needs #include <iostream>.
- "\n" ends a line; std::endl also flushes.
- Escapes: \n \t \" \\
std::cout << "x = " << x << "\n";Common mistake: Using >> with cout. Output arrows point toward cout: <<.
Reading with std::cin
Read values from the keyboard with >>.
- cin >> stops at whitespace.
- Use std::getline(std::cin, line) to read a full line.
- Check input: if (!(std::cin >> n)) { /* invalid */ }
int age;
std::cin >> age;Fundamental types
Common built-in types.
- int: whole numbers
- double: decimal numbers
- char: one character in single quotes
- bool: true or false
- std::string (from <string>): text
int n = 5;
double pi = 3.14159;
char grade = 'A';
bool done = false;
const int MAX = 100;Integer division
Dividing two ints throws away the decimal part.
- 7 / 2 is 3.
- 7.0 / 2 is 3.5.
- % gives the remainder: 7 % 2 is 1.
Common mistake: Writing 9 / 5 in a formula and getting 1 instead of 1.8.
Compilation stages
Preprocess, compile, link, then run.
- Preprocessor: handles #include and #define, producing one translation unit.
- Compiler: turns each translation unit into an object file (.o / .obj).
- Linker: joins object files and libraries into an executable.
- Linker errors ("undefined reference") mean a declared function was never defined.
g++ -c main.cpp # compile only -> main.o
g++ main.o -o app # link
./app # runCommon mistake: Confusing a compile error (syntax/type) with a linker error (missing definition).
Variables and constants
A variable is a named, typed piece of memory.
- Declare before use: type name = value;
- Always initialise: reading an uninitialised local is undefined behaviour.
- const: value cannot change after initialisation.
- constexpr (C++11): value known at compile time.
int score = 0;
const double TAX = 0.17;
constexpr int DAYS = 7;
int count{5}; // brace init, C++11Common mistake: int total; total += 5; // total had no starting value
Type sizes and ranges
Sizes are platform-dependent, check with sizeof.
- char: exactly 1 byte.
- int: at least 16 bits, usually 32.
- long long: at least 64 bits.
- double: usually 64-bit floating point, ~15 significant digits.
- unsigned types cannot hold negatives and wrap around on overflow.
std::cout << sizeof(int) << "\n";Common mistake: Assuming int is always 4 bytes on every system.
Identifier rules
Rules for naming variables, functions and types.
- Letters, digits and _ only; cannot start with a digit.
- Case-sensitive: total and Total differ.
- Cannot be a keyword (int, class, return...).
- Avoid names starting with _ followed by a capital, or containing __ (reserved).
- Prefer descriptive names: studentCount, not sc.
Common mistake: int 2nd = 5; // starts with a digit
Arithmetic operators
+ - * / % on numbers.
- int / int truncates toward zero: -7 / 2 is -3.
- % works only on integers; sign follows the left operand.
- Dividing an integer by 0 is undefined behaviour.
- Mix in a double to get a decimal result: 7 / 2.0 is 3.5.
int a = 17, b = 5;
std::cout << a / b << " " << a % b; // 3 2Common mistake: double avg = sum / count; // both int: decimals lost before assignment
cin pitfalls
Mixing >> and getline, and failed reads.
- After cin >> x, a newline remains in the buffer.
- Call std::cin.ignore(...) before std::getline.
- On bad input cin enters a fail state; clear() then ignore().
std::cin >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, name);Arrays
Fixed-size, same-type, zero-indexed.
- Valid indexes: 0 to size - 1.
- int a[5] = {}; zeros every element.
- Out-of-bounds access is undefined behaviour.
- Arrays cannot be assigned or compared with = / ==.
- Function parameters lose the size: pass n separately.
- 2D: a[row][col]; parameters need every size except the first.
- std::array<int, N> knows its size and has .at().
const int N = 3;
int a[N] = {4, 7, 1};
for (int i = 0; i < N; ++i) std::cout << a[i];Common mistake: for (int i = 0; i <= N; ++i) reads one past the end.
std::string
Resizable text from <string>.
- + joins, += appends, == and < compare.
- .size() / .length() count characters.
- .find(x) returns a position or std::string::npos.
- .substr(pos, count), .insert, .erase, .replace.
- std::getline(std::cin >> std::ws, s) reads a full line.
- C-strings (char[]) end with '\0' and need size + 1.
std::string s = "user@site";
auto at = s.find('@');
if (at != std::string::npos) std::cout << s.substr(0, at);Common mistake: "a" + "b" does not compile: two literals are not std::string.
std::vector
The default resizable container.
- push_back / pop_back at the end.
- insert / erase take iterators: v.begin() + i.
- size() = elements, capacity() = allocated space.
- v(3, 0) = three zeros; v{3, 0} = the values 3 and 0.
- Growth can invalidate references and iterators.
- for (auto& x : v) to modify, const auto& to read.
- sort + unique + erase removes duplicates.
std::vector<int> v = {3, 1, 2};
v.push_back(5);
std::sort(v.begin(), v.end());Common mistake: v[0] = 1; on an empty vector: there is no element 0 yet.
Pointers
A pointer stores an address.
- int* p = &x; stores x's address.
- *p reads or writes x; p->m is (*p).m.
- Initialise every pointer, use nullptr for 'none'.
- p + i moves i elements; a[i] is *(a + i).
- const int* p: read-only target; int* const p: fixed pointer.
- Reference: alias, never null, cannot re-bind.
int x = 5;
int* p = &x;
*p = 9; // x is now 9
if (p) std::cout << *p;Common mistake: Dereferencing nullptr, an uninitialised pointer or a pointer to a dead local.
Dynamic memory & smart pointers
Own heap objects with RAII types.
- new/delete and new[]/delete[] must match.
- Leak: memory never freed. Dangling: pointer to freed memory.
- RAII: acquire in constructor, release in destructor.
- unique_ptr (single owner, move-only), make_unique is C++14.
- shared_ptr counts owners; weak_ptr observes and breaks cycles.
- Base classes used through pointers need a virtual destructor.
- Check with -fsanitize=address,undefined.
auto p = std::make_unique<Item>(1);
auto q = std::move(p); // p is now nullCommon mistake: Two shared_ptrs pointing at each other never free their objects.
Classes & OOP
User-defined types, encapsulation, inheritance and polymorphism.
- struct defaults to public, class to private.
- Keep data private; enforce invariants in member functions.
- Constructors: use initialiser lists; mark single-argument ones explicit.
- Destructors run in reverse order of construction.
- Public inheritance = is-a; composition = has-a (prefer it for reuse).
- virtual + override for runtime polymorphism; = 0 makes a class abstract.
- Polymorphic bases need virtual ~Base() = default;
- Rule of zero (RAII members) first; rule of five when owning a raw resource.
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
};Common mistake: Storing derived objects in std::vector<Base> slices them: store std::unique_ptr<Base>.
File and string streams
Read and write files with <fstream>, parse text with <sstream>.
- ifstream reads, ofstream writes, fstream does both.
- ofstream truncates by default; std::ios::app appends.
- Check if (!in) after opening: failed streams fail silently.
- Read in the loop condition: while (std::getline(in, line)) or while (in >> x).
- Never control a loop with eof().
- Streams close themselves when destroyed (RAII).
- istringstream parses a line; ostringstream builds text, .str() returns it.
std::ifstream in("data.txt");
if (!in) { std::cerr << "cannot open data.txt\n"; return 1; }
std::string line;
while (std::getline(in, line)) {
std::istringstream ss(line);
int a, b;
if (ss >> a >> b) std::cout << a + b << '\n';
}Common mistake: while (!in.eof()) processes the last item twice.
Exceptions
throw an error, catch it where it can be handled.
- throw stops the function; stack unwinding destroys locals.
- catch by const reference: catch (const std::exception& e).
- Order catch clauses specific to general; catch (...) last.
- throw; rethrows the current exception.
- logic_error (preventable bug) vs runtime_error (runtime problem).
- vector::at throws out_of_range; stoi throws invalid_argument / out_of_range.
- Custom errors derive from std::runtime_error.
- Never throw from destructors.
try {
risky();
} catch (const std::out_of_range& e) {
std::cerr << "range: " << e.what() << '\n';
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}Common mistake: Catching std::exception before more specific types, so they never run.
Debugging, assertions and testing
Find bugs with tools, not guesses.
- Debug build: g++ -std=c++17 -g -O0 -Wall -Wextra.
- VS Code: F9 breakpoint, F5 continue, F10 over, F11 into, Shift+F11 out.
- Compiler messages: file:line:col: error: text. Fix the first error first.
- 'undefined reference' is a linker error.
- assert checks assumptions; removed by -DNDEBUG, so no side effects inside.
- static_assert is checked at compile time.
- Test normal, edge and error cases; separate logic from I/O.
#include <cassert>
assert(index < v.size() && "index in range");
static_assert(sizeof(int) >= 4, "need 32-bit int");Common mistake: Using assert to validate user input.
Choosing an STL container
Pick a container from how the data is used.
- vector: default; fast index and push_back.
- array: fixed size known at compile time.
- deque: fast at both ends.
- list: stable iterators, no indexing.
- map/set: sorted, O(log n). unordered_*: hashed, average O(1), no order.
Common mistake: Linear-searching a vector for every lookup instead of using a map or set.
Iterators
Objects that point into containers and connect them to algorithms.
- Range is [begin, end); never dereference end().
- Categories: forward, bidirectional, random-access.
- rbegin/rend reverse; cbegin/cend const.
- std::next / std::distance work for every iterator.
for (auto it = v.begin(); it != v.end(); )
it = (*it < 0) ? v.erase(it) : std::next(it);Common mistake: Using an iterator after erase or push_back invalidated it.
stack, queue, priority_queue
Restricted interfaces over another container.
- stack: LIFO, push/top/pop.
- queue: FIFO, push/front/back/pop.
- priority_queue: top() is largest; std::greater for smallest.
- pop() returns void; check empty() first.
std::priority_queue<int, std::vector<int>, std::greater<int>> minQ;set and map
Sorted trees: unique keys, O(log n) operations.
- set: unique sorted values; multiset allows duplicates.
- map[key] inserts a default value if missing.
- Use find/count/at to check without inserting.
- multimap has no [].
for (const auto& [key, value] : m) std::cout << key << ' ' << value << '\n';Common mistake: if (m[k] == 0) silently inserts k.
unordered_set and unordered_map
Hash tables: average O(1) lookup, no order.
- Same interface as set/map.
- Iteration order is unspecified.
- Custom key types need a hash and ==.
- Worst case O(n) with many collisions.
Algorithms, comparators and lambdas
Ready-made loops from <algorithm> and <numeric>.
- find returns last if not found.
- binary_search needs sorted data.
- Comparator must be strict: < not <=.
- Lambda: [capture](params) { body }; [x] copy, [&x] reference.
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });Common mistake: Using <= in a comparator.
Modern C++ essentials
Everyday features from C++11 to C++20, with their standards.
- auto, range-for, nullptr, enum class, brace init: C++11.
- make_unique, generic lambdas, auto return: C++14.
- Structured bindings, optional, variant, if constexpr, CTAD: C++17.
- Concepts, modules, range-for init-statement: C++20.
- Compile with -std=c++17 or -std=c++20 to enable them.
if (auto [it, ok] = m.insert({k, v}); !ok) { /* already there */ }Common mistake: Using a feature newer than your compiler's -std setting.
Templates and concepts
Generic code generated per type at compile time.
- template <typename T> T f(T x);
- Define templates in headers.
- Deduction must agree: f(1, 2.0) fails for f(T, T).
- template <> = full specialization; partial only for class templates.
- C++20: template <std::integral T> constrains T.
template <std::integral T>
bool isEven(T n) { return n % 2 == 0; }Common mistake: Putting template definitions in a .cpp file.
Big-O and complexity
How work and memory grow with input size n.
- O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ).
- Drop constants and smaller terms.
- Sequential phases add; nested loops multiply.
- Halving each step gives O(log n).
- Space complexity counts extra memory, including recursion depth.
Common mistake: Judging speed from one timing on tiny input.
Searching and sorting
Classic algorithms and their costs.
- Linear search O(n); binary search O(log n) on sorted data.
- Bubble/selection/insertion O(n²); insertion is fast on nearly sorted data.
- Merge sort O(n log n), O(n) space, stable.
- Quicksort average O(n log n), worst O(n²); std::sort is introsort.
int mid = lo + (hi - lo) / 2;Common mistake: Binary search on unsorted data.
Linked lists, stacks, queues, hash tables
Core structures and their operation costs.
- Linked list: O(1) insert at a known node, O(n) access.
- Stack LIFO, queue FIFO, both O(1).
- Hash table: average O(1), worst O(n); load factor = items / buckets.
Trees and heaps
Hierarchical structures.
- BST: left < node < right; operations O(height).
- Balanced trees keep height O(log n) (std::map).
- Traversals: pre, in (sorted for BST), post, level (queue).
- Heap in array: children 2i+1, 2i+2; push/pop O(log n).
Graphs, BFS and DFS
Vertices, edges and how to explore them.
- Adjacency list O(V + E) memory; matrix O(V²).
- BFS (queue): shortest paths in unweighted graphs.
- DFS (recursion/stack): components, cycles, topological order.
- Both are O(V + E).
std::vector<std::vector<int>> adj(V);Common mistake: Marking visited in BFS only when popping.
Recursion and backtracking
Solve a problem with smaller copies of itself.
- Every recursion needs a reachable base case.
- Backtracking: choose, explore, un-choose.
- Prune branches that cannot succeed.
- Depth costs stack space.
Problem-solving patterns
Clues that point to a technique.
- Sorted input → binary search / two pointers.
- Contiguous range → sliding window / prefix sums.
- Seen before? → hash set or map.
- Repeating subproblems → dynamic programming.
- Locally best choice provably optimal → greedy.
- Top k → heap.
Common mistake: Trusting a greedy rule without a proof or counterexample check.
Lifetime, UB and safety
Advanced rules that explain many bugs.
- Locals die at block end in reverse order; temporaries at the end of the full expression.
- lvalue = has identity; rvalue = temporary or std::move'd.
- C++17 guarantees elision when returning a prvalue.
- Undefined behavior: out of bounds, dangling, signed overflow, uninitialised reads, null deref, data races.
- Exception guarantees: basic, strong (copy and swap), nothrow.
Common mistake: Returning a reference to a local variable.
Threads and synchronisation
Running work concurrently without data races.
- std::jthread (C++20) joins automatically; std::thread must be joined or detached.
- Shared writes need std::atomic or a mutex.
- Lock with lock_guard / scoped_lock (RAII).
- condition_variable: always wait with a predicate.
- scoped_lock(m1, m2) avoids deadlock.
std::scoped_lock lock(a.m, b.m);Common mistake: Incrementing a plain int from several threads.
Building, testing and maintaining
Tools and habits for real projects.
- CMake: cmake -S . -B build, then cmake --build build.
- include/ for headers, src/ for code, tests/ for tests.
- Warnings: -Wall -Wextra (-Werror for your code).
- Sanitizers: -fsanitize=address,undefined; thread separately.
- Measure with a profiler before optimising.
- Test normal, edge and error cases; name things clearly.
g++ -std=c++17 -g -O1 -Wall -Wextra -fsanitize=address,undefined main.cppCommon mistake: Optimising before measuring.
Literals
Values written directly in code.
- Integers: 42, 0x2A (hex), 052 (octal), 0b101010 (binary, C++14).
- Suffixes: 10u unsigned, 10L long, 10LL long long, 3.0f float.
- Digit separators (C++14): 1'000'000.
- Raw strings: R"(C:\path\file)" keep backslashes as typed.
- nullptr is the null pointer literal; true/false are bool.
long long big = 9'000'000'000LL;
auto path = R"(C:\temp\a.txt)";Common mistake: Writing 010 and expecting ten: a leading 0 means octal (8).
Operator precedence
Which operator binds first when there are no brackets.
- Unary (! - ++) before * / %, before + -.
- Shifts << >> come before comparisons < >.
- Comparisons before == !=, before &, ^, |, then &&, then ||.
- Assignment = and ?: bind last (right to left).
- When unsure, add brackets.
bool ok = (x & 1) == 0; // brackets neededCommon mistake: x & 1 == 0 means x & (1 == 0), not (x & 1) == 0.
Floating point arithmetic
float and double are approximations.
- 0.1 + 0.2 is not exactly 0.3.
- Compare with a tolerance: std::abs(a - b) < 1e-9.
- Prefer double over float.
- Dividing a double by 0.0 gives inf or nan, not a crash.
- Never use floating point for money: store cents in integers.
if (std::abs(a - b) < 1e-9) std::cout << "equal\n";Common mistake: if (0.1 + 0.2 == 0.3) is false.
Bit operators and manipulation
Work on individual bits of integers.
- & AND, | OR, ^ XOR, ~ NOT, << left shift, >> right shift.
- Set bit k: x |= (1u << k). Clear: x &= ~(1u << k).
- Toggle: x ^= (1u << k). Test: (x >> k) & 1.
- x & (x - 1) clears the lowest set bit; power of two if result is 0 (and x > 0).
- C++20 <bit>: std::popcount, std::has_single_bit.
- Use unsigned types for bit work.
unsigned flags = 0;
flags |= 1u << 3; // set bit 3
bool on = (flags >> 3) & 1u; // trueCommon mistake: Shifting by >= the type's width is undefined behaviour.
Loops
for, while, do-while and range-for.
- for (init; condition; step) when the count is known.
- while (condition) when it is not.
- do { } while (cond); runs at least once.
- Range-for: for (const auto& x : v).
- break leaves the loop; continue skips to the next round.
for (int i = 0; i < 5; ++i) std::cout << i;
int n = 0;
do { ++n; } while (n < 3);Common mistake: while (x < 10); with a semicolon loops forever doing nothing.
Flow control
if, else, switch and jumps.
- if (init; cond) is allowed since C++17.
- switch works on integers, chars and enums.
- Each case needs break, or use [[fallthrough]] on purpose.
- default handles every other value.
- return ends a function; goto exists but avoid it.
switch (grade) {
case 'A': std::cout << "Top"; break;
case 'B': std::cout << "Good"; break;
default: std::cout << "Keep going";
}Common mistake: Forgetting break, so the next case also runs.
Stream manipulators (iomanip)
Format output with <iomanip>.
- std::fixed << std::setprecision(2): two decimals.
- std::setw(n): width of the next item only.
- std::left / std::right: alignment.
- std::setfill('0'): padding character.
- std::boolalpha prints true/false; std::hex prints hexadecimal.
std::cout << std::fixed << std::setprecision(2) << 3.14159; // 3.14
std::cout << std::setw(5) << std::setfill('0') << 42; // 00042Common mistake: Expecting setw to stay active: it resets after one output.
const, mutable and const correctness
Promise that something will not change.
- const int x = 5; cannot be reassigned.
- Pass big objects as const T& to avoid copies.
- Member function marked const cannot change the object.
- mutable members can change even inside const functions (e.g. a cache).
- Only const member functions can be called on a const object.
class Counter {
int n = 0;
public:
int get() const { return n; }
void add() { ++n; }
};Common mistake: Forgetting const on a getter, so it cannot be used on const objects.
Functions, overloading and inline
Reusable named blocks of code.
- Declare before use, or put a prototype above main.
- Overloading: same name, different parameter types.
- Default arguments go on the right: void f(int a, int b = 0).
- Return several values with a struct, std::pair or std::tuple.
- inline allows a definition in a header without linker errors.
int area(int s) { return s * s; }
int area(int w, int h) { return w * h; }Common mistake: Overloads that differ only in return type do not compile.
Pass by value vs reference
Copy the argument, or refer to the original.
- By value (int x): function gets a copy.
- By reference (int& x): function changes the caller's variable.
- By const reference (const T& x): no copy, no change.
- Small types (int, double) by value; big ones by const reference.
- References must be bound when created and cannot be null.
void addOne(int& x) { ++x; }
int a = 1;
addOne(a); // a is 2Common mistake: Expecting void addOne(int x) to change the caller's value.
The this pointer
Inside a member function, this points to the current object.
- this->name separates a member from a parameter with the same name.
- return *this; allows chaining calls.
- In a const member function, this points to const.
struct Box {
int w = 0;
Box& setW(int w) { this->w = w; return *this; }
};friend
Give a function or class access to private members.
- Declare inside the class: friend void show(const Box&);
- Common for operator<< output.
- Friendship is not inherited or mutual.
- Use sparingly: it weakens encapsulation.
Operator overloading
Give operators meaning for your own types.
- Arithmetic: return a new value, e.g. Vec operator+(Vec a, const Vec& b).
- Compound (+=) return *this by reference.
- operator<< for printing is a non-member: std::ostream& operator<<(std::ostream&, const T&).
- C++20: auto operator<=>(const T&) const = default; generates comparisons.
- Keep the usual meaning; do not make + subtract.
struct Vec {
int x, y;
Vec& operator+=(const Vec& o) { x += o.x; y += o.y; return *this; }
};
Vec operator+(Vec a, const Vec& b) { return a += b; }Special member functions and rule of 3/5/0
Constructors, destructor, copy and move operations.
- Default constructor, destructor, copy ctor, copy assignment, move ctor, move assignment.
- Rule of zero: use std::string, vector, unique_ptr and write none of them.
- Rule of three/five: if you write one (e.g. a destructor freeing memory), write all.
- = default asks for the generated version; = delete forbids it.
- Copy assignment should handle self-assignment.
class NoCopy {
public:
NoCopy() = default;
NoCopy(const NoCopy&) = delete;
NoCopy& operator=(const NoCopy&) = delete;
};Common mistake: Writing a destructor that deletes a pointer but keeping the default copy: double delete.
Namespaces and headers
Group names and split code into files.
- namespace app { void run(); } then call app::run().
- Headers (.h/.hpp) hold declarations; .cpp files hold definitions.
- Protect headers with #pragma once or include guards.
- Never write using namespace std; in a header.
- One definition rule: a function is defined once across the program (inline excepted).
// math.hpp
#pragma once
namespace math { int square(int x); }Common mistake: Defining a non-inline function in a header included by two .cpp files.
Enumerations
Named sets of constants.
- enum class Color { Red, Green }; is scoped and type-safe (C++11).
- Use Color::Red; no implicit conversion to int.
- static_cast<int>(c) to get the number.
- Pick the underlying type: enum class Small : unsigned char { A, B };
enum class Dir { Up, Down };
Dir d = Dir::Up;
if (d == Dir::Up) std::cout << "up";Common mistake: Plain enum values leak into the outer scope and clash.
pair, tuple, optional, variant, any
Small vocabulary types.
- std::pair<A, B>: .first, .second.
- std::tuple: many values; unpack with auto [a, b, c].
- std::optional<T> (C++17): a value or nothing; check has_value().
- std::variant<A, B> (C++17): one of several types; use std::visit.
- std::any (C++17): any type, read with std::any_cast.
std::optional<int> find(int k) { if (k > 0) return k; return std::nullopt; }
if (auto r = find(3)) std::cout << *r;Common mistake: Reading *opt when it is empty: undefined behaviour; use value_or.
Lambdas and std::function
Callable objects you can store and pass around.
- Lambda: [captures](params) -> ret { body }.
- [=] copies everything used, [&] references it; prefer naming captures.
- mutable lets a lambda change its copied captures.
- std::function<int(int)> stores any callable with that signature (small overhead).
- Pass callables to templates directly for speed.
int base = 10;
auto add = [base](int x) { return base + x; };
std::function<int(int)> f = add;
std::cout << f(5); // 15Common mistake: Capturing a local by reference in a lambda that outlives it.
Random numbers
Use <random>, not rand().
- Engine: std::mt19937 gen(std::random_device{}());
- Distribution: std::uniform_int_distribution<int> d(1, 6);
- Call d(gen) for each number.
- Create the engine once, not inside a loop.
- Fixed seed gives repeatable results for testing.
std::mt19937 gen(std::random_device{}());
std::uniform_int_distribution<int> dice(1, 6);
std::cout << dice(gen);Common mistake: rand() % 6 is biased and low quality.
Preprocessor
Text processing before compilation.
- #include pastes a file.
- #define makes macros; prefer constexpr and inline functions.
- #if / #ifdef / #endif for conditional code.
- Macros ignore scope and types.
- Wrap macro arguments in brackets: #define SQ(x) ((x) * (x)).
#ifdef DEBUG
std::cerr << "debug mode\n";
#endifCommon mistake: #define SQ(x) x * x makes SQ(1 + 2) equal 5.
Type conversions and casts
Convert between types explicitly.
- static_cast<T>: normal conversions (double to int).
- dynamic_cast<T*>: safe downcast in polymorphic classes; nullptr on failure.
- const_cast: removes const (rarely correct).
- reinterpret_cast: raw bit reinterpretation; avoid.
- Avoid C-style (int)x: it hides which cast happens.
double d = 3.7;
int n = static_cast<int>(d); // 3Common mistake: Narrowing silently: int x = 3.9; becomes 3. Brace init int x{3.9}; refuses.
auto, decltype and type aliases
Let the compiler work out types.
- auto drops top-level const and references; use const auto& to keep them.
- decltype(expr) gives the exact declared type.
- using Id = long long; is the modern typedef.
- Trailing return: auto f() -> int.
- Templates can use aliases: template <class T> using Vec = std::vector<T>;
using Grid = std::vector<std::vector<int>>;
auto it = m.find(key); // long iterator type spelled for youCommon mistake: auto x = {1}; makes std::initializer_list<int>, not int.
Move semantics and perfect forwarding
Transfer resources instead of copying them.
- T&& binds to temporaries (rvalues).
- std::move(x) casts to rvalue; x is left valid but unspecified.
- Move constructor steals the buffer and leaves the source empty; mark it noexcept.
- In templates, T&& + std::forward<T>(x) keeps the argument's category.
- Returning a local by value is moved or elided automatically.
std::vector<std::string> names;
std::string s = "long text";
names.push_back(std::move(s)); // no copyCommon mistake: return std::move(local); can block copy elision.
Compile-time programming
Compute and check things while compiling.
- constexpr functions can run at compile time.
- if constexpr picks a branch per type (C++17).
- <type_traits>: std::is_integral_v<T>, std::is_same_v<A, B>.
- Variadic templates: template <class... Ts>; fold: (args + ...).
- SFINAE and enable_if are the older way; prefer concepts (C++20).
- CRTP: class D : public Base<D> gives static polymorphism.
template <class... Ts>
auto sum(Ts... xs) { return (xs + ... + 0); }
static_assert(sum(1, 2, 3) == 6);Virtual functions and RTTI
Choose behaviour at runtime.
- virtual functions are dispatched through a vtable.
- override catches signature mistakes; final stops further overriding.
- Calling virtual functions in constructors uses the base version.
- typeid(obj).name() gives an implementation-defined name.
- dynamic_cast checks the real type of a polymorphic object.
struct Animal { virtual ~Animal() = default; virtual void speak() const = 0; };
struct Dog : Animal { void speak() const override { std::cout << "Woof"; } };Design patterns: Pimpl, Singleton, Observer
Common structures in C++ projects.
- Pimpl: keep private data in a hidden Impl struct behind unique_ptr to cut rebuild times.
- Singleton: static local in a function (Meyers singleton) is thread-safe since C++11.
- Observer: subjects keep a list of callbacks (std::function).
- Factory: function returning std::unique_ptr<Base>.
- Patterns serve design; do not force them.
Config& config() {
static Config instance; // created once, thread-safe
return instance;
}Futures, promises and async
Get a result from another thread.
- std::async(std::launch::async, f) runs f and returns a std::future.
- future.get() waits and returns the result (once).
- std::promise sets a value that a future receives.
- Exceptions thrown in the task come back through get().
- Semaphores (C++20): std::counting_semaphore limits concurrent access.
auto fut = std::async(std::launch::async, [] { return 6 * 7; });
std::cout << fut.get(); // 42chrono and regex
Time and pattern matching from the standard library.
- std::chrono::steady_clock::now() for measuring durations.
- duration_cast<milliseconds>(end - start).count().
- Literals: using namespace std::chrono_literals; 500ms, 2s.
- std::regex_match checks the whole string; regex_search finds a part.
- std::regex is slow to construct: build it once.
auto t0 = std::chrono::steady_clock::now();
// work
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - t0).count();Undefined, unspecified and implementation-defined
Three kinds of behaviour the standard does not fix.
- Undefined: anything can happen (out of bounds, signed overflow, use after free).
- Unspecified: one of several valid results (order of evaluating f(a(), b())).
- Implementation-defined: compiler chooses and documents it (sizeof(int)).
- Sanitizers catch many undefined cases at runtime.
- Never rely on 'it worked on my machine'.
int i = 0;
// i = i++ + ++i; // undefined before C++17 rules: never write thisCommon mistake: Assuming signed integer overflow wraps around.
Scope, storage and linkage
Where variables live and who can see them.
- Block scope: lives until the closing }.
- static local: created once, keeps its value between calls.
- static at file level or anonymous namespace: visible in this file only.
- extern declares a variable defined in another file.
- inline variables (C++17) can be defined in headers.
- thread_local: one copy per thread.
int counter() {
static int n = 0;
return ++n; // 1, 2, 3...
}Attributes
Hints to the compiler in [[double brackets]].
- [[nodiscard]]: warn if the return value is ignored.
- [[maybe_unused]]: silence unused warnings.
- [[fallthrough]]: intentional switch fallthrough.
- [[deprecated("why")]]: warn on use.
- [[likely]] / [[unlikely]] (C++20): branch hints.
[[nodiscard]] bool save();
// save(); // warning: result ignoredCommon compiler and linker errors
Read the first error carefully.
- 'was not declared in this scope': missing include, typo or wrong order.
- 'expected ; before': missing semicolon on the previous line.
- 'undefined reference to': declared but not defined, or file not linked.
- 'multiple definition of': function defined in a header without inline.
- 'no matching function for call': wrong argument types or count.
Common mistake: Fixing the 50th error first: later errors often disappear after fixing the first.
Optimization and profiling
Make code faster where it matters.
- Release build: -O2 (or -O3) and -DNDEBUG.
- Profile first (perf, gprof, Visual Studio profiler).
- Better algorithm beats micro tricks.
- Reserve vector capacity; avoid needless copies; keep data contiguous.
- Measure again after every change.
std::vector<int> v;
v.reserve(1'000'000); // one allocation instead of manyUnit testing
Small automatic checks for each function.
- Popular frameworks: GoogleTest, Catch2, doctest.
- Test one behaviour per test with a clear name.
- Cover normal, edge (empty, zero, max) and error cases.
- Run tests on every change (CMake + ctest).
- Keep logic separate from input/output so it is testable.
TEST_CASE("square") {
CHECK(square(3) == 9);
CHECK(square(0) == 0);
}Value categories: lvalue, prvalue, xvalue
Every expression is an lvalue, prvalue or xvalue.
- lvalue: has a name/identity, you can take its address (x, v[0], *p).
- prvalue: a pure temporary value (42, a + b, f() returning by value).
- xvalue: an expiring object, e.g. std::move(x).
- glvalue = lvalue or xvalue; rvalue = prvalue or xvalue.
- T&& binds to rvalues; const T& binds to everything.
- C++17 guarantees copy elision when returning a prvalue.
int x = 1;
int& a = x; // lvalue
int&& b = x + 1; // prvalue
int&& c = std::move(x); // xvalueCommon mistake: Thinking std::move moves: it only casts to an xvalue; the move constructor does the work.
Forwarding references and std::forward
Pass arguments on while keeping lvalue/rvalue-ness.
- In template<class T> void f(T&& x), T&& is a forwarding reference.
- std::forward<T>(x) keeps an rvalue as rvalue, lvalue as lvalue.
- Used by make_unique, emplace_back and wrappers.
- auto&& in range-for is also a forwarding reference.
template <class T>
void wrap(T&& arg) { use(std::forward<T>(arg)); }Common mistake: Using std::move on a forwarding reference: it moves from the caller's lvalues.
Type traits and if constexpr
Ask questions about types at compile time.
- <type_traits>: std::is_integral_v<T>, std::is_same_v<A,B>, std::remove_cvref_t<T>.
- if constexpr (cond) discards the false branch at compile time (C++17).
- static_assert(cond, "msg") stops compilation if false.
- C++20 concepts (std::integral T) replace most enable_if tricks.
template <class T>
std::string kind(T) {
if constexpr (std::is_integral_v<T>) return "integer";
else return "other";
}Common mistake: Using a plain if: both branches must compile for every T.
SFINAE and concepts
Restrict which types a template accepts.
- SFINAE: a failed substitution removes an overload instead of erroring.
- std::enable_if_t<cond, int> = 0 is the classic form.
- C++20: template <std::integral T> or requires clauses are clearer.
- Write your own: template<class T> concept Addable = requires(T a){ a + a; };
template <class T>
concept Addable = requires(T a) { a + a; };
Addable auto twice(Addable auto x) { return x + x; }chrono durations and clocks
Type-safe time maths with <chrono>.
- Durations: std::chrono::seconds, milliseconds; literals 5s, 250ms with using namespace std::chrono_literals.
- duration_cast<milliseconds>(d) converts and truncates.
- steady_clock for measuring elapsed time; system_clock for wall time.
- time_point - time_point gives a duration.
- .count() returns the raw number.
auto t0 = std::chrono::steady_clock::now();
work();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0).count();Common mistake: Timing code with system_clock: it can jump when the clock is adjusted.
regex_match vs regex_search
Whole-string match or find anywhere.
- std::regex_match: the whole string must match.
- std::regex_search: finds the first match anywhere.
- std::smatch m; m[1] holds capture group 1.
- std::sregex_iterator loops over every match.
- std::regex_replace(s, re, "$1") rewrites text.
- Use raw strings R"(\d+)" to avoid double escaping.
std::regex num(R"((\d+))");
std::smatch m;
if (std::regex_search(s, m, num)) std::cout << m[1];Common mistake: Using regex_match to find a number inside a sentence: it returns false.
Exception safety guarantees
What state remains after something throws.
- No-throw: never throws (mark noexcept), e.g. destructors and swap.
- Strong: either it succeeds or nothing changed (copy-and-swap).
- Basic: no leaks, object still valid but may be changed.
- RAII (unique_ptr, lock_guard) gives the basic guarantee for free.
- Move constructors should be noexcept so vector can use them.
Widget& operator=(Widget other) noexcept { // copy-and-swap
swap(*this, other);
return *this;
}Common mistake: Throwing from a destructor: during stack unwinding this calls std::terminate.
Lambda captures in depth
How lambdas see outside variables.
- [x] copies, [&x] references, [=] / [&] capture all used.
- [this] captures the object pointer; [*this] copies the object (C++17).
- Init capture: [p = std::move(ptr)] moves into the lambda (C++14).
- mutable allows changing copied captures.
- Generic lambda: [](auto a, auto b) { return a < b; }.
auto counter = [n = 0]() mutable { return ++n; };
counter(); // 1
counter(); // 2Common mistake: Capturing a local by reference and calling the lambda after the local is gone.