C++
Modern C++ reference - syntax, the STL, classes, templates, smart pointers, move semantics, concurrency, and C++20/23 features.
Sign in to mark items as known and track your progress.
Sign inGetting Started
Your first program, compiling, and running C++.
Hello World
The entry point and console output.
// Quick Reference
#include <iostream>
int main() {
std::cout << "Hello, World!\n";
}Compile & Run
Build with a modern standard and useful warnings.
// Quick Reference
g++ -std=c++23 -Wall main.cpp -o main
./mainVariables & Types
Fundamental types, inference, constants, and casts.
Types & auto
Built-in types and type inference.
// Quick Reference
int i = 42;
double d = 3.14;
bool b = true;
char c = 'A';
auto x = 10; // inferred intconst, constexpr & Casts
Immutability and explicit conversions.
// Quick Reference
const int MAX = 100; // runtime constant
constexpr int SIZE = 10; // compile-time constant
int n = static_cast<int>(3.9); // 3Operators
Arithmetic, comparison, logical, and bitwise.
Operators
The everyday operator set.
// Quick Reference
+ - * / % // arithmetic
== != < > <= >= // comparison
&& || ! // logical
& | ^ ~ << >> // bitwise
cond ? a : b // ternaryStrings
std::string, string_view, and formatting.
std::string
The owning, mutable string type.
// Quick Reference
#include <string>
std::string s = "hello";
s.size(); s.substr(1, 3);
s += " world"; s.find("world");string_view & std::format
Cheap views and modern formatting.
// Quick Reference
#include <string_view>
#include <format>
void log(std::string_view msg); // no copy
std::string s = std::format("{} = {}", "x", 42);Control Flow
Branching and looping.
Conditionals & switch
if/else and switch, including init-statements.
// Quick Reference
if (x > 0) { ... } else if (x < 0) { ... } else { ... }
switch (n) {
case 1: ...; break;
default: ...;
}Loops
for, range-for, while, and do-while.
// Quick Reference
for (int i = 0; i < 5; i++) { ... }
for (auto x : container) { ... } // range-for
while (cond) { ... }
do { ... } while (cond);Functions
Declaring, overloading, and passing arguments.
Functions & Overloading
Signatures, defaults, and overloads.
// Quick Reference
int add(int a, int b) { return a + b; }
int add(int a, int b, int c); // overload
void greet(std::string name = "friend"); // default argPassing Arguments
By value, reference, const reference, and pointer.
// Quick Reference
void byValue(int x); // copy
void byRef(int& x); // can modify caller's variable
void byConstRef(const std::string& s); // no copy, read-only
void byPtr(int* p); // pointerReferences & Pointers
Aliases and addresses.
References & Pointers
The two indirection mechanisms and when to use each.
// Quick Reference
int n = 5;
int& ref = n; // alias - must bind on init, never rebinds
int* ptr = &n; // address of n
*ptr = 10; // dereference to read/write
int* none = nullptr;Arrays & Vectors
Dynamic and fixed-size sequences.
std::vector
The default resizable array.
// Quick Reference
#include <vector>
std::vector<int> v = {1, 2, 3};
v.push_back(4);
v[0]; v.size();
v.erase(v.begin());std::array & C-arrays
Fixed-size sequences.
// Quick Reference
#include <array>
std::array<int, 3> a = {1, 2, 3};
a.size(); a[0];
int c[3] = {1, 2, 3}; // C-styleSTL Containers
Maps, sets, and tuples.
map & unordered_map
Key-value associative containers.
// Quick Reference
#include <map> // ordered
#include <unordered_map> // hashed
std::unordered_map<std::string, int> m;
m["a"] = 1; m.at("a");
m.count("a"); m.contains("a"); // C++20set, pair & tuple
Unique collections and fixed groupings.
// Quick Reference
#include <set>
std::set<int> s = {3, 1, 2}; // sorted, unique
std::pair<int, std::string> p{1, "a"};
auto t = std::make_tuple(1, 2.0, "x");Algorithms & Iterators
The <algorithm> and <numeric> workhorses.
Algorithms
Sort, search, transform, and accumulate.
// Quick Reference
#include <algorithm>
std::sort(v.begin(), v.end());
std::find(v.begin(), v.end(), x);
auto n = std::count_if(v.begin(), v.end(), pred);Lambdas & std::function
Anonymous functions and callable wrappers.
Lambdas
Inline callables with captures.
// Quick Reference
auto add = [](int a, int b) { return a + b; };
int factor = 3;
auto mul = [factor](int x) { return x * factor; }; // capture by value
auto ref = [&sum](int x) { sum += x; }; // capture by referenceEnums & Structs
Named constants and plain data.
Enums & Structs
enum class and aggregate structs.
// Quick Reference
enum class Color { Red, Green, Blue };
Color c = Color::Red;
struct Point { int x; int y; };
Point p{3, 4};Classes & Objects
Encapsulation, lifetime, and operators.
Classes & Constructors
Members, access, and the member initializer list.
// Quick Reference
class Person {
public:
Person(std::string n) : name(n) {}
std::string getName() const { return name; }
private:
std::string name;
};Destructors, static & RAII
Deterministic cleanup and class-level members.
// Quick Reference
class File {
public:
File(const char* p) { f = fopen(p, "r"); } // acquire
~File() { if (f) fclose(f); } // release
private:
FILE* f = nullptr;
};Operator Overloading & Rule of Five
Custom operators and copy/move control.
// Quick Reference
struct Vec2 {
double x, y;
Vec2 operator+(const Vec2& o) const { return {x+o.x, y+o.y}; }
};
std::ostream& operator<<(std::ostream& os, const Vec2& v);Inheritance & Polymorphism
Base classes and virtual dispatch.
Inheritance
Deriving classes and reusing behavior.
// Quick Reference
class Animal {
public:
Animal(std::string n) : name(n) {}
protected:
std::string name;
};
class Dog : public Animal {
public:
Dog(std::string n) : Animal(n) {}
};Virtual & Polymorphism
Dynamic dispatch, abstract classes, and casts.
// Quick Reference
class Shape {
public:
virtual double area() const = 0; // pure virtual -> abstract
virtual ~Shape() = default; // virtual destructor
};
class Circle : public Shape {
double area() const override { return 3.14159 * r * r; }
double r;
};Templates & Concepts
Generic code and constraints.
Templates
Function and class templates.
// Quick Reference
template <typename T>
T max(T a, T b) { return a > b ? a : b; }
template <typename T>
class Box { T value; };Concepts (C++20)
Constrain template parameters readably.
// Quick Reference
#include <concepts>
template <std::integral T>
T doubleIt(T x) { return x * 2; }Smart Pointers & Move Semantics
Automatic memory management and efficient transfers.
Smart Pointers
Owning pointers that free themselves.
// Quick Reference
#include <memory>
auto u = std::make_unique<int>(42); // sole owner
auto s = std::make_shared<int>(42); // ref-counted
std::weak_ptr<int> w = s; // non-owning observerMove Semantics
Transfer resources instead of copying.
// Quick Reference
std::vector<int> a = {1, 2, 3};
std::vector<int> b = std::move(a); // steal a's buffer, no copy
// a is now valid-but-unspecified (usually empty)Exceptions
Errors that unwind the stack.
Exceptions
throw, try/catch, and noexcept.
// Quick Reference
try {
throw std::runtime_error("boom");
} catch (const std::exception& e) {
std::cerr << e.what();
}File & Stream I/O
Reading and writing with streams.
File I/O
fstream and stringstream.
// Quick Reference
#include <fstream>
std::ofstream out("data.txt");
out << "hello\n";
std::ifstream in("data.txt");
std::string line;
std::getline(in, line);Concurrency
Threads, synchronization, and async.
Threads & Mutex
Running work in parallel safely.
// Quick Reference
#include <thread>
#include <mutex>
std::thread t([]{ work(); });
t.join();
std::mutex m;
std::lock_guard<std::mutex> lock(m);async, future & atomic
Results from background work and lock-free counters.
// Quick Reference
#include <future>
auto fut = std::async([]{ return 40 + 2; });
int result = fut.get(); // 42
#include <atomic>
std::atomic<int> count{0};
count++; // atomic, no mutexNumbers, Date/Time & Regex
Math, time, randomness, and pattern matching.
Numbers & Math
<cmath>, <random>, and numeric limits.
// Quick Reference
#include <cmath>
std::sqrt(16.0); std::pow(2, 10);
std::abs(-5); std::round(3.6);
#include <limits>
std::numeric_limits<int>::max();Date/Time & Regex
std::chrono and std::regex.
// Quick Reference
#include <chrono>
auto start = std::chrono::steady_clock::now();
// ...
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start);Modern C++ (C++20/23)
Recent language and library additions.
Utility Types & Structured Bindings
optional, variant, and destructuring.
// Quick Reference
#include <optional>
std::optional<int> find();
if (auto r = find()) use(*r);
auto [a, b] = std::pair{1, 2}; // structured bindingsRanges, format & C++23
Pipelines, formatting, and the newest additions.
// Quick Reference
#include <ranges>
auto evens = v | std::views::filter([](int x){ return x%2==0; })
| std::views::transform([](int x){ return x*x; });