C++
Printed from:
C++ Cheatsheet
Language Overview
C++ is a powerful, high-performance, general-purpose programming language that extends C with object-oriented, generic, and functional programming features. Developed by Bjarne Stroustrup, it provides low-level memory manipulation with high-level abstractions, making it ideal for system programming, game development, embedded systems, and performance-critical applications. The current ISO standard is C++23 (ISO/IEC 14882:2024), with C++26 under active development.
Key Characteristics
- Compiled language
- Statically typed
- Support for procedural, object-oriented, generic, and functional programming
- Direct hardware manipulation
- Zero-overhead abstractions
- Strong type checking
- Deterministic resource management via RAII
Basic Syntax
Hello World
1234567#include <iostream>
int main() {
std::cout << "Hello, World!\n";
return 0;
}
Hello World (C++23 with std::print)
1234567#include <print>
int main() {
std::print("Hello, {}!\n", "World");
return 0;
}
Program Structure
123456789101112131415161718// Preprocessor directives
#include <header_file>
// Or, with C++20 modules
import std;
// Function declaration
return_type function_name(parameters) {
// Function body
return value;
}
// Main function - entry point of the program
int main() {
// Program logic
return 0;
}
Avoid
using namespace std;at file scope; prefer explicitstd::qualification or scopedusingdeclarations.
Data Types
Primitive Types
1234567891011121314151617181920212223242526272829303132// Integer Types
short // at least 16-bit signed integer
int // at least 16-bit signed integer (commonly 32-bit)
long // at least 32-bit signed integer
long long // at least 64-bit signed integer (C++11)
// Fixed-width Integer Types (<cstdint>)
std::int8_t, std::int16_t, std::int32_t, std::int64_t
std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t
std::size_t, std::ptrdiff_t
// Floating Point Types
float // typically 32-bit IEEE 754
double // typically 64-bit IEEE 754
long double // Extended precision floating point
// Fixed-format Floating Point (C++23, <stdfloat>)
std::float16_t, std::float32_t, std::float64_t, std::float128_t, std::bfloat16_t
// Character Types
char // 8-bit character
wchar_t // Wide character
char8_t // UTF-8 code unit (C++20)
char16_t // UTF-16 code unit
char32_t // UTF-32 code unit
// Boolean Type
bool // true or false
// Void Type
void // Represents absence of value
Collection Types (Standard Template Library)
1234567891011121314151617181920212223242526272829303132// Sequence Containers
std::array<int, 5> fixed_array; // Fixed-size array
std::vector<int> dynamic_array; // Dynamic array
std::deque<int> double_ended; // Double-ended queue
std::list<int> linked_list; // Doubly-linked list
std::forward_list<int> single_list; // Singly-linked list
std::span<int> view{dynamic_array}; // Non-owning view (C++20)
// String Views and Strings
std::string text;
std::string_view view_text; // Non-owning string view (C++17)
// Associative Containers
std::set<int> unique_sorted_set; // Unique sorted elements
std::multiset<int> sorted_multiset; // Sorted with duplicates allowed
std::map<std::string, int> kv_map; // Sorted key-value pairs
std::unordered_map<std::string, int> hash_map; // Hash table implementation
std::flat_map<std::string, int> fmap; // Sorted contiguous map (C++23)
std::flat_set<int> fset; // Sorted contiguous set (C++23)
// Container Adapters
std::stack<int> stack; // LIFO container
std::queue<int> queue; // FIFO container
std::priority_queue<int> p_queue; // Priority-based queue
// Utility Types
std::optional<int> maybe_value; // Optional value (C++17)
std::variant<int, std::string> v; // Type-safe union (C++17)
std::any anything; // Type-erased value (C++17)
std::expected<int, Error> result; // Value-or-error (C++23)
std::tuple<int, double, std::string> t;
Variables and Constants
Variable Declarations
1234567891011121314151617int age = 25; // Explicit type
auto inferred = 3.14; // Type inference (C++11)
const int MAX_VALUE = 100; // Runtime/compile-time constant
constexpr int COMPILE_TIME = 42; // Compile-time constant (C++11)
constinit int eager_init = 0; // Constant-initialized (C++20)
consteval int immediate(int x); // Must run at compile time (C++20)
// Type Qualifiers / Specifiers
volatile int sensor_value; // Can change unexpectedly
static int file_scope_var; // Internal linkage / class-shared
extern int global_var; // Declared in another translation unit
inline int header_var = 0; // Inline variables (C++17)
thread_local int per_thread; // Thread-local storage
// Structured Bindings (C++17)
auto [x, y, z] = std::tuple{1, 2.0, "three"};
Operators
Arithmetic Operators
1234567int a = 10, b = 3;
int sum = a + b; // Addition
int diff = a - b; // Subtraction
int prod = a * b; // Multiplication
int div = a / b; // Division
int mod = a % b; // Modulus
Comparison Operators
12345678bool is_equal = (a == b); // Equal to
bool is_not_equal = (a != b); // Not equal to
bool greater = (a > b); // Greater than
bool less_equal = (a <= b); // Less than or equal to
// Three-way comparison (C++20)
auto ord = (a <=> b); // std::strong_ordering / partial_ordering / weak_ordering
Logical Operators
12345bool x = true, y = false;
bool and_op = x && y; // Logical AND
bool or_op = x || y; // Logical OR
bool not_op = !x; // Logical NOT
Control Structures
Conditional Statements
1234567891011121314151617181920212223242526272829303132// If-Else
if (condition) {
// Code block
} else if (another_condition) {
// Alternative block
} else {
// Default block
}
// If with initializer (C++17)
if (auto it = map.find(key); it != map.end()) {
use(it->second);
}
// constexpr if (C++17) and consteval if (C++23)
if constexpr (std::is_integral_v<T>) { /* compile-time branch */ }
// Ternary Operator
int result = condition ? value_if_true : value_if_false;
// Switch Statement (with [[fallthrough]] attribute, C++17)
switch (variable) {
case 1:
do_one();
[[fallthrough]];
case 2:
do_two();
break;
default:
break;
}
Loops
123456789101112131415161718// For Loop
for (int i = 0; i < 10; ++i) {
// Repeated code block
}
// Range-based For Loop (C++11), with initializer (C++20)
for (auto numbers = make_data(); int num : numbers) {
// Iterate through elements
}
// While / Do-While
while (condition) { /* ... */ }
do { /* executed at least once */ } while (condition);
// Loop Control
break; // Exit loop
continue; // Skip current iteration
Functions
Basic Function Definition
1234567891011121314151617181920212223// Function declaration
return_type function_name(parameter_type parameter) {
return value;
}
// Function with default arguments
void greet(std::string_view name = "World") {
std::cout << "Hello, " << name << "!\n";
}
// Function overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
// Trailing return type / auto deduction
auto multiply(int a, int b) -> int { return a * b; }
// Abbreviated function templates (C++20)
auto square(auto x) { return x * x; }
// [[nodiscard]] (C++17), [[noreturn]], [[deprecated]] attributes
[[nodiscard]] int compute();
Lambda Functions
123456789101112auto lambda = [](int x, int y) { return x + y; };
// Capture clauses
int multiplier = 2;
auto multiply = [multiplier](int x) { return x * multiplier; };
// Generic lambdas (C++14), template-parameter lambdas (C++20)
auto generic = []<typename T>(T a, T b) { return a + b; };
// constexpr / consteval lambdas, mutable lambdas
auto counter = [n = 0]() mutable { return ++n; };
Object-Oriented Programming
Classes and Objects
12345678910111213141516171819202122232425262728293031class Person {
private:
std::string name;
int age{};
public:
// Constructor with member initializer list
Person(std::string n, int a) : name(std::move(n)), age(a) {}
// Defaulted special members
Person() = default;
Person(const Person&) = default;
Person(Person&&) noexcept = default;
Person& operator=(const Person&) = default;
Person& operator=(Person&&) noexcept = default;
~Person() = default;
void introduce() const {
std::cout << "Name: " << name << ", Age: " << age << '\n';
}
// Three-way comparison (C++20)
auto operator<=>(const Person&) const = default;
const std::string& getName() const noexcept { return name; }
void setName(std::string n) { name = std::move(n); }
};
Person p1("John", 30);
p1.introduce();
Inheritance and Polymorphism
123456789101112131415161718192021222324252627class Student : public Person {
private:
std::string school;
public:
Student(std::string n, int a, std::string s)
: Person(std::move(n), a), school(std::move(s)) {}
void displaySchool() const {
std::cout << "School: " << school << '\n';
}
};
// Virtual functions, override, final
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0; // Pure virtual
};
class Circle final : public Shape {
public:
double area() const override { return 3.14159 * r * r; }
private:
double r{1.0};
};
Concepts (C++20)
12345678910#include <concepts>
template <std::integral T>
T gcd(T a, T b) {
return b == 0 ? a : gcd(b, a % b);
}
template <typename T>
concept Addable = requires(T a, T b) { { a + b } -> std::convertible_to<T>; };
Error Handling
Exception Handling
12345678910try {
if (error_condition) {
throw std::runtime_error("An error occurred");
}
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << '\n';
} catch (...) {
std::cerr << "Unknown exception\n";
}
throw()exception specifications andstd::unexpected_handlerwere removed in C++17. Usenoexceptinstead.
std::expected (C++23)
12345678910#include <expected>
std::expected<int, std::string> parse(std::string_view s);
if (auto r = parse("42"); r) {
use(*r);
} else {
std::cerr << r.error() << '\n';
}
File I/O
1234567891011121314151617181920#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
// Writing to a file
std::ofstream outfile("example.txt");
outfile << "Hello, File!\n";
// Reading from a file (RAII closes automatically)
std::ifstream infile("example.txt");
std::string line;
while (std::getline(infile, line)) {
std::cout << line << '\n';
}
// Filesystem operations (C++17)
for (const auto& entry : fs::directory_iterator(".")) {
std::cout << entry.path() << '\n';
}
Memory Management
Pointers and References
123456789101112131415int x = 10;
int* ptr = &x; // Raw pointer
int& ref = x; // Reference
// Smart Pointers (prefer over raw new/delete)
auto unique = std::make_unique<int>(10); // C++14
auto shared = std::make_shared<int>(20); // C++11
std::weak_ptr<int> weak = shared; // Non-owning observer
// Arrays
auto arr = std::make_unique<int[]>(100); // C++14
auto sarr = std::make_shared<int[]>(100); // C++20
// Avoid manual new/delete in new code
Move Semantics
123std::vector<int> source = {1, 2, 3};
std::vector<int> sink = std::move(source); // O(1) transfer of resources
Modern C++ Features
Modules (C++20)
12345678// hello.cppm
export module hello;
export void greet() { std::print("Hi!\n"); }
// main.cpp
import hello;
int main() { greet(); }
Coroutines (C++20)
12345#include <coroutine>
// Building blocks for co_await, co_yield, co_return.
// Higher-level coroutine types (generators, tasks) ship with
// std::generator in C++23 and via third-party libraries (cppcoro, etc.).
Ranges and Views (C++20, expanded in C++23)
123456789101112#include <ranges>
#include <vector>
std::vector<int> v = {1, 2, 3, 4, 5, 6};
auto even_squares = v
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; });
// C++23: std::ranges::to, zip, enumerate, chunk, slide, etc.
auto squared = v | std::views::transform([](int n){ return n*n; })
| std::ranges::to<std::vector>();
Formatting and Printing (C++20 / C++23)
1234567#include <format>
#include <print>
std::string s = std::format("{} + {} = {}", 2, 3, 2 + 3);
std::print("{:>10}\n", "right"); // C++23
std::println("Hello, {}!", "world"); // C++23
Designated Initializers (C++20)
123struct Point { int x; int y; };
Point p{.x = 1, .y = 2};
Concurrency
123456789101112131415161718#include <thread>
#include <mutex>
#include <atomic>
#include <future>
std::jthread t([](std::stop_token st) { // C++20: auto-joining, stoppable
while (!st.stop_requested()) { /* work */ }
});
std::mutex m;
{
std::scoped_lock lock(m); // C++17, multi-lock capable
}
std::atomic<int> counter{0};
counter.fetch_add(1, std::memory_order_relaxed);
auto fut = std::async(std::launch::async, []{ return 42; });
int v = fut.get();
std::atomic_ref(C++20) andstd::latch,std::barrier,std::counting_semaphoreprovide modern coordination primitives.
Build Systems and Tools
Compilation
1234567# Compile with a modern standard
g++ -std=c++23 -O2 -Wall -Wextra -Wpedantic -o program source.cpp
clang++ -std=c++23 -O2 -Wall -Wextra -o program source.cpp
# MSVC
cl /std:c++latest /W4 /O2 source.cpp
CMake Basic Configuration
123456789cmake_minimum_required(VERSION 3.28) # Needed for C++20 modules support project(MyProject LANGUAGES CXX) set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) add_executable(program main.cpp)
Package Managers
- vcpkg — Microsoft's open-source C/C++ package manager
- Conan — Decentralized, multi-platform C/C++ package manager
- CPM.cmake — CMake-based dependency manager
Tooling
- clang-format — code formatting
- clang-tidy — static analysis and modernization
- cppcheck, include-what-you-use, sanitizers (ASan, UBSan, TSan, MSan)
Popular Libraries
Standard Ecosystem
{fmt}— origin ofstd::format/std::print- Abseil, GSL (Guidelines Support Library)
Boost Libraries
- Boost.Asio (networking, source of the in-progress C++ networking TS)
- Boost.Beast (HTTP/WebSocket on top of Asio)
- Boost.Filesystem (subset standardized into
std::filesystem) - Boost.Serialization, Boost.Algorithm, Boost.Hana
Qt Framework
- Cross-platform GUI development
- Extensive widget and QML library
- Signal-slot mechanism
Other Notable Libraries
- Eigen (linear algebra), Catch2 / GoogleTest (testing)
- spdlog (logging), nlohmann/json (JSON), cppcoro (coroutines)
Best Practices
Performance Tips
- Prefer stack allocation and value semantics over heap allocation
- Pass large objects by
const&or by value with move - Use move semantics and
noexceptwhere appropriate - Mark small, frequently called functions
inlineorconstexpr - Profile before optimizing; trust the optimizer
Code Style and Safety
- Follow the C++ Core Guidelines
- Use RAII for all resources; avoid raw
new/delete - Prefer
enum classover plainenum - Use
const,constexpr, and[[nodiscard]]whenever meaningful - Prefer standard algorithms and ranges over hand-rolled loops
- Initialize variables (use brace initialization to catch narrowing)
- Avoid
using namespace std;at namespace scope
Testing Frameworks
Google Test
123456#include <gtest/gtest.h>
TEST(MyTest, Addition) {
EXPECT_EQ(add(2, 3), 5);
}
Catch2 (v3+)
123456#include <catch2/catch_test_macros.hpp>
TEST_CASE("Addition works") {
REQUIRE(add(2, 3) == 5);
}
doctest
1234567#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest/doctest.h>
TEST_CASE("Addition") {
CHECK(add(2, 3) == 5);
}
Resources for Further Learning
Books
- "A Tour of C++" (3rd ed., covers C++20) by Bjarne Stroustrup
- "Effective Modern C++" by Scott Meyers (C++11/14)
- "C++ Software Design" by Klaus Iglberger
- "C++ Concurrency in Action" (2nd ed.) by Anthony Williams
- "C++20: The Complete Guide" / "C++23 in Detail" by Nicolai Josuttis / Bartłomiej Filipek
- "C++ Primer" (5th ed.) by Stanley Lippman
Online Resources
- cppreference.com
- isocpp.org and the C++ Core Guidelines
- Compiler Explorer (godbolt.org)
- CppCon, Meeting C++, and ACCU conference videos
Learning Platforms
- learncpp.com
- Coursera and edX C++ courses
- hackingcpp.com (visual guides and cheatsheets)
Note: This cheatsheet provides a comprehensive overview of C++ through the C++23 standard. Always refer to the latest language standards (C++23, with C++26 in progress) and your compiler's documentation for the most up-to-date information.
Continue Learning
Discover more cheatsheets to boost your productivity