I/O Manipulators
Format stream output with width, fill, precision, base, and more.
#include <iomanip> std::cout#include <iostream> << std::fixed#include <iostream> << std::setprecision#include <iomanip>(2) << 3.14159; // 3.14Object Slicing
Copying a derived object into a base object loses the derived part.
Derived d; Base b = d; // Sliced. Base& r = d; // Not sliced.Operator Overload
Define what operators do for a class.
Point operator+(const Point& a, const Point& b) { return Point(a.x + b.x, a.y + b.y); } Point c = a + b;Move Semantics
Transfer an object's resources to another object instead of copying them.
std::vector#include <vector><int> a = {1, 2, 3}; std::vector#include <vector><int> b = std::move#include <utility>(a); // b owns the array and a is empty.Range
Work with whole containers and compose lazy views.
#include <ranges> std::vector#include <vector><int> v = {1, 2, 3}; auto odds = v | std::views::filter#include <ranges>(is_odd); // odds is {1, 3}.Unique Pointer
Smart pointer that is the sole owner of its managed resource.
#include <memory> std::unique_ptr#include <memory><int> p = std::make_unique#include <memory><int>(5); *p; // 5 // Deleted when p goes out of scope.Weak Pointer
Non-owning reference to an object managed by a shared pointer.
#include <memory> auto s = std::make_shared#include <memory><int>(5); std::weak_ptr#include <memory><int> w = s; if (auto p = w.lock()) { *p; // 5 }Container
Standard library class templates that store collections of elements.
std::vector#include <vector><int> v = {1, 2, 3}; std::set#include <set><int> s = {1, 2, 3}; std::map#include <map><char, int> m = {{'a', 42}};File Stream
Read from and write to files with streams.
#include <fstream> std::ofstream#include <fstream> out("out.txt"); out << "hello\n";Stream
Read and write sequences of characters with a common interface.
void print(std::ostream#include <iostream>& os, int x) { os << x << "\n"; } print(std::cout#include <iostream>, 1); print(std::cerr#include <iostream>, 2);String Stream
Read from and write to strings with streams.
#include <sstream> std::ostringstream#include <sstream> ss; ss << "x = " << 42; ss.str(); // "x = 42"Copy-and-Swap Idiom
Safe implementation of copy and move assignment.
Buffer& operator=(Buffer other) { std::swap#include <utility>(size, other.size); std::swap#include <utility>(data, other.data); return *this; }Defaulted Function
Give function compiler-generated default version.
class Foo { public: Foo() = default; ~Foo() = default; };Deleted Function
Make a function unusable.
void foo(); void foo(int) = delete;Copy Assignment
Operator that copies another object's resources to an existing object.
Buffer a(10); Buffer b(20); b = a;Copy Constructor
Constructor that creates an object by copying another object's resources.
Buffer a(10); Buffer b = a;Move Assignment
Operator that moves another object's resources to an existing object.
Buffer a(10); Buffer b(20); b = std::move#include <utility>(a);Move Constructor
Constructor that creates an object by taking another object's resources.
Buffer a(10); Buffer b = std::move#include <utility>(a);Remove-Erase Idiom
Remove elements from a container that match a value or condition.
std::vector#include <vector><int> v = {1, 2, 1, 3}; v.erase(std::remove#include <algorithm>(v.begin(), v.end(), 1), v.end()); v; // [2, 3]Rule of Three/Five/Zero
Guidelines for which special member functions a class should define.
class Person { public: std::string#include <string> name; std::vector#include <vector><int> scores; }; // Rule of zero: no special members needed.Shared Pointer
Smart pointer that can share ownership of its managed resource.
#include <memory> std::shared_ptr#include <memory><int> a = std::make_shared#include <memory><int>(5); std::shared_ptr#include <memory><int> b = a; a.use_count(); // 2Smart Pointer
Pointer that manages its own memory allocation and freeing.
#include <memory> std::unique_ptr#include <memory><int> u = std::make_unique#include <memory><int>(5); std::shared_ptr#include <memory><int> s = std::make_shared#include <memory><int>(6);Static
Bind variable lifetime to its translation unit.
int next_id() { static int id = 0; return ++id; } next_id(); // 1 next_id(); // 2Type Alias
Provide an alternative name for a type.
using Point = std::pair#include <utility><int, int>; Point p(1, -2);Exception
Report and handle errors with throw, try and catch.
try { throw std::runtime_error#include <stdexcept>("Oops."); } catch (const std::exception#include <exception>& e) { e.what(); // "Oops." }Expected
Hold a value or an error.
#include <expected> std::expected<int, std::string#include <string>> r = std::unexpected("Oops."); r.has_value(); // false r.error(); // "Oops."Algorithm
Standard library functions that operate on containers.
#include <algorithm> std::vector#include <vector><int> v = {3, 1, 2}; std::sort#include <algorithm>(v.begin(), v.end()); // {1, 2, 3}Getline
Read a line of input into a string.
std::string#include <string> line; std::getline#include <string>(std::cin#include <iostream>, line);Iterator
Object that points to an element in a container.
std::vector#include <vector><int> v = {1, 2, 3}; auto it = v.begin(); *it; // 1 ++it;Dynamic Cast
Safely convert a base class pointer or reference to a derived class.
Shape* s = new Circle(); Circle* c = dynamic_cast<Circle*>(s); // OK. Square* q = dynamic_cast<Square*>(s); // Null pointer.Friend
Give a function or class access to private members.
class Account { double balance; friend void audit(const Account& a); };Optional
Hold a value or nothing.
#include <optional> std::optional#include <optional><int> x; x.has_value(); // false x = 5; *x; // 5Virtual Destructor
Destroy a derived object correctly through a base class pointer.
class Shape { public: virtual ~Shape() {} }; Shape* s = new Circle(); delete s;Array
Fixed-size array of the same type.
#include <array> std::array#include <array><int, 3> arr = {1, 2, 3}; arr.size(); // 3Map
Sorted collection of key-value pairs with unique keys.
#include <map> std::map#include <map><std::string#include <string>, int> ages; ages["Alice"] = 30; ages["Alice"]; // 30Set
Sorted collection of unique elements.
#include <set> std::set#include <set><int> s = {3, 1, 2, 1}; // {1, 2, 3} s.count(2); // 1String
Sequence of characters.
#include <string> std::string#include <string> s = "hello"; s += " world"; s.size(); // 11Tie
Unpack a tuple or pair into existing variables.
#include <tuple> int a; int b; std::tie#include <tuple>(a, b) = std::make_tuple#include <tuple>(1, 2);Vector
Dynamic array of the same type.
#include <vector> std::vector#include <vector><int> v; v.push_back(1); v.push_back(2); v.size(); // 2Lambda
Unnamed function object that can capture variables from the surrounding scope.
auto foo = [var](int arg) -> int { return arg * var; };Pair
Holds two values of possibly different types.
#include <utility> std::pair#include <utility><char, int> p('c', 30); p.first; // 'c' p.second; // 30Tuple
Holds a fixed number of values of possibly different types.
#include <tuple> std::tuple#include <tuple><std::string#include <string>, int, double> t("alice", 30, 1.7); std::get#include <tuple><0>(t); // "alice"Constructor
Member function that runs when an object is created.
class Circle { public: Circle(double r) : radius(r) {} double radius; }; Circle c(2.0);Converting Constructor
Constructor that implicitly converts a value into the class type.
class Circle { public: Circle(double r) : radius(r) {} double radius; }; Circle c = 2.0; // Implicit conversion.Destructor
Member function that runs when an object is destroyed.
class Buffer { public: Buffer() : data(new int[8]) {} ~Buffer() { delete[] data; } int* data; };This Pointer
Pointer to the current object.
class Circle { public: void setRadius(double radius) { this->radius = radius; } double radius; };Class
User-defined type that groups data and functions.
class Circle { public: double area() { return 3.14 * radius * radius; } double radius; };Const Method
Member function that cannot modify the object it is called on.
class Foo { public: int get() const { return val; } private: int val; };Default Constructor
Constructor that can be called with no arguments.
class Foo { public: Foo() : val(0) {} int val; }; Foo obj; // Calls Foo().Static Member
Class member shared by all objects of a class.
class Shape { public: static int count; }; Shape::count;New and Delete
Allocate and free memory at runtime.
int* ptr = new int(1); delete ptr; int* arr = new int[3]{1, 2, 3}; delete[] arr;Pointer
Variable that stores the memory address of another variable.
int var = 1; int* ptr = &var; // Address of var. *ptr = 2; // var = 2.Reference
Alias for an existing variable.
int var = 1; int& ref = var; // ref is an alias for var. ref = 2; // var is now 2.Auto
Automatic type deduction of an object or expression at compile time.
auto x = 123; // int auto y = x + 456; // int auto z = "str"; // const char*Static Cast
Explicitly convert a value to another type at compile time.
double d = 3.99; int i = static_cast<int>(d); // 3Default Argument
A function parameter uses a default value when the caller omits it.
void greet(std::string#include <string> name = "world"); greet(); // Hello world greet("there"); // Hello thereFunction Overloading
Define multiple functions with the same name but different parameters.
void print(int i); void print(double d); void print(std::string#include <string> s);Implicit Type Conversion
Automatic conversion between types performed by the compiler.
int i = 3.99; // 3, fractional part discarded double d = 3; // 3.0 bool b = 42; // trueConst Variable
Declare a variable whose value cannot change after initialisation.
const int size = 100; size = 200; // ERROR.Iterator-Based For Loop
Loop over containers with STL iterators.
for (auto it = c.begin(); it != c.end(); ++it) { *it; }Multiple Inheritance
Subclass extending from multiple base classes.
class Base1 {}; class Base2 {}; class Derived : public Base1, public Base2 {};Abstract Class
Class that cannot be instantiated but can be used as a base class for inheritance.
class Base { virtual void f() = 0; };Inheritance
Create a new class using another class as a base to extend from.
class Base {}; class Derived : Base {};Virtual Function
Member functions that can be overridden in derived classes.
class Base { virtual void f() {} } class Derived : Base { virtual void f() override {} }Enumeration
User-defined data type to give integer constants meaningful names.
enum class Status { Stopped, Running, Paused };Member Initialiser List
Initialise class member variables before the constructor body runs.
class Foo { Foo(int arg) : val(arg) {} int val; };Character Input
Read from standard input using I/O streams.
#include <iostream> std::cin#include <iostream> >> var;Character Output
Write to standard output using I/O streams.
#include <iostream> std::cout#include <iostream> << var << "\n";Delegating Constructor
Reduce constructor boilerplate by delegating to another constructor in the same class.
class Foo { Foo(int x) : Foo(x, 'y') {} Foo(int x, char y) : x(x), y(y) {} };Namespace
Groups identifiers to a named scope to prevent name collisions.
namespace GroupA { int var = 1; } GroupA::var;Access Specifier
Set class member accessibility.
class Example { public: protected: private: };Range-Based For Loop
Loop over containers without writing indices or iterators.
for (auto& element : container) { // Do something with element. }Boolalpha
Print booleans as "true"/"false" strings instead of the default 1/0.
std::cout#include <iostream> << std::boolalpha#include <iostream> << true << "\n" << false << "\n";Functor
Objects that are callable like functions and with internal state.
Doubler obj(1); obj(); // value = 2 obj(); // value = 4Structured Binding
Unpack pairs, tuples, and aggregates cleanly.
auto [x, y] = std::pair#include <utility>{1, 2};