Skip to content
AgileLogics

C++ Cheat Sheet

Learn C++ from the basics →

Basics

std::cout << "Hi" << std::endl;
Console output
std::string name = "Ada";
Standard library string type
auto x = 5;
Type inference
int &ref = x;
Reference — an alias for x, not a pointer

Classes

class Dog { public: void bark(); private: std::string name; };
Class with access specifiers
Dog(std::string n) : name(n) {}
Constructor with a member initializer list
class Dog : public Animal { };
Public inheritance
virtual void speak() = 0;
Pure virtual function (abstract)

STL Containers

std::vector<int> v = {1, 2, 3};
Dynamic array
std::map<std::string, int> m;
Ordered key/value map
std::unordered_map<std::string, int> m;
Hash-based key/value map
std::set<int> s;
Unique, sorted elements

Smart Pointers & RAII

std::unique_ptr<T> p = std::make_unique<T>();
Sole-ownership smart pointer
std::shared_ptr<T> p = std::make_shared<T>();
Reference-counted smart pointer
{ std::lock_guard<std::mutex> lock(m); }
RAII — lock released automatically at scope end

Templates & Lambdas

template<typename T> T max(T a, T b) { return a > b ? a : b; }
Function template
template<typename T> class Box { T value; };
Class template
auto add = [](int a, int b) { return a + b; };
Lambda expression

Exceptions

try { risky(); } catch (const std::exception &e) { }
Catch by const reference
throw std::runtime_error("bad input");
Throw a standard exception type