C++
Updated: September 8, 2025Categories: Languages
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.
Key Characteristics
- Compiled language
- Statically typed
- Support for procedural, object-oriented, and generic programming
- Direct hardware manipulation
- Zero-overhead abstractions
- Strong type checking
Basic Syntax
Hello World
C++
1234567#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Program Structure
C++
123456789101112131415161718// Preprocessor directives
#include <header_file>
// Namespace declaration
using namespace 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;
}
Data Types
Primitive Types
C++
1234567891011121314151617181920212223// Integer Types
short // 16-bit signed integer
int // 32-bit signed integer
long // 64-bit signed integer
long long // Extended integer type
// Floating Point Types
float // 32-bit floating point
double // 64-bit floating point
long double // Extended precision floating point
// Character Types
char // 8-bit character
wchar_t // Wide character
char16_t // 16-bit Unicode character
char32_t // 32-bit Unicode character
// Boolean Type
bool // true or false
// Void Type
void // Represents absence of value
Collection Types (Standard Template Library)
C++
1234567891011121314151617// Sequence Containers
std::array<int, 5> fixed_array; // Fixed-size array
std::vector<int> dynamic_array; // Dynamic array
std::list<int> linked_list; // Doubly-linked list
std::forward_list<int> single_list; // Singly-linked list
// Associative Containers
std::set<int> unique_sorted_set; // Unique sorted elements
std::multiset<int> sorted_multiset; // Sorted with duplicates allowed
std::map<string, int> key_value_map; // Key-value pairs with unique keys
std::unordered_map<string, int> hash_map; // Hash table implementation
// Container Adapters
std::stack<int> stack; // LIFO container
std::queue<int> queue; // FIFO container
std::priority_queue<int> p_queue; // Priority-based queue
Variables and Constants
Variable Declarations
C++
12345678910int age = 25; // Explicit type
auto dynamic_type = 3.14; // Type inference (C++11)
const int MAX_VALUE = 100; // Constant value
constexpr int COMPILE_TIME = 42; // Compile-time constant
// Type Qualifiers
volatile int sensor_value; // Can change unexpectedly
static int class_variable; // Shared across class instances
extern int global_var; // Declared in another file
Operators
Arithmetic Operators
C++
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
C++
12345bool 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
Logical Operators
C++
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
C++
123456789101112131415161718192021222324// If-Else
if (condition) {
// Code block
} else if (another_condition) {
// Alternative block
} else {
// Default block
}
// Ternary Operator
int result = (condition) ? value_if_true : value_if_false;
// Switch Statement
switch (variable) {
case constant1:
// Code block
break;
case constant2:
// Another block
break;
default:
// Default block
}
Loops
C++
12345678910111213141516171819202122232425// For Loop
for (int i = 0; i < 10; ++i) {
// Repeated code block
}
// Range-based For Loop (C++11)
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
// Iterate through elements
}
// While Loop
while (condition) {
// Repeated code block
}
// Do-While Loop
do {
// Executed at least once
} while (condition);
// Loop Control
break; // Exit loop
continue; // Skip current iteration
Functions
Basic Function Definition
C++
1234567891011121314151617181920// Function declaration
return_type function_name(parameter_type parameter) {
// Function body
return value;
}
// Function with default arguments
void greet(string name = "World") {
std::cout << "Hello, " << name << "!" << std::endl;
}
// Function overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
Lambda Functions (C++11)
C++
1234567auto lambda = [](int x, int y) { return x + y; };
int result = lambda(3, 4); // Returns 7
// Capture clause
int multiplier = 2;
auto multiply = [multiplier](int x) { return x * multiplier; };
Object-Oriented Programming
Classes and Objects
C++
1234567891011121314151617181920212223class Person {
private:
string name;
int age;
public:
// Constructor
Person(string n, int a) : name(n), age(a) {}
// Member functions
void introduce() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
// Getter and Setter
string getName() const { return name; }
void setName(string n) { name = n; }
};
// Object creation
Person p1("John", 30);
p1.introduce();
Inheritance
C++
123456789101112class Student : public Person {
private:
string school;
public:
Student(string n, int a, string s) : Person(n, a), school(s) {}
void displaySchool() {
std::cout << "School: " << school << std::endl;
}
};
Error Handling
Exception Handling
C++
12345678910111213try {
// Code that might throw an exception
if (error_condition) {
throw std::runtime_error("An error occurred");
}
} catch (const std::exception& e) {
// Handle specific exceptions
std::cerr << "Caught exception: " << e.what() << std::endl;
} catch (...) {
// Catch all other exceptions
std::cerr << "Unknown exception" << std::endl;
}
File I/O
C++
123456789101112131415#include <fstream>
// Writing to a file
std::ofstream outfile("example.txt");
outfile << "Hello, File!" << std::endl;
outfile.close();
// Reading from a file
std::ifstream infile("example.txt");
string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
infile.close();
Memory Management
Pointers and References
C++
123456789101112int x = 10;
int* ptr = &x; // Pointer to x
int& ref = x; // Reference to x
// Dynamic Memory Allocation
int* dynamic_int = new int(42);
delete dynamic_int; // Manual memory deallocation
// Smart Pointers (C++11)
std::unique_ptr<int> unique_ptr(new int(10));
std::shared_ptr<int> shared_ptr = std::make_shared<int>(20);
Modern C++ Features
Auto and Type Inference
C++
1234auto x = 42; // int
auto pi = 3.14159; // double
auto vec = std::vector<int>{1, 2, 3};
Range-based Algorithms
C++
12345std::vector<int> numbers = {1, 2, 3, 4, 5};
std::for_each(numbers.begin(), numbers.end(), [](int n) {
std::cout << n << " ";
});
Build Systems and Tools
Compilation
Bash
123456789# Compile with g++
g++ -std=c++11 -o program source.cpp
# Compile with optimization
g++ -O3 -std=c++17 source.cpp
# Link multiple files
g++ file1.cpp file2.cpp -o program
CMake Basic Configuration
cmake
123456cmake_minimum_required(VERSION 3.10) project(MyProject) set(CMAKE_CXX_STANDARD 17) add_executable(program main.cpp)
Popular Libraries
Boost Libraries
- Boost.Filesystem
- Boost.Serialization
- Boost.Algorithm
- Boost.Asio for networking
Qt Framework
- Cross-platform GUI development
- Extensive widget library
- Signal-slot mechanism
Best Practices
Performance Tips
- Use references over pointers when possible
- Prefer stack allocation over heap
- Use move semantics (C++11)
- Minimize copies, use const references
- Use inline functions for small, frequently called functions
Code Style
- Use meaningful variable and function names
- Follow consistent indentation
- Use const whenever possible
- Prefer standard library implementations
- Use RAII for resource management
Testing Frameworks
Google Test
C++
123456#include <gtest/gtest.h>
TEST(MyTest, Addition) {
EXPECT_EQ(add(2, 3), 5);
}
Catch2
C++
1234567#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
TEST_CASE("Addition works") {
REQUIRE(add(2, 3) == 5);
}
Resources for Further Learning
Books
- "Effective Modern C++" by Scott Meyers
- "C++ Primer" by Stanley Lippman
- "The C++ Programming Language" by Bjarne Stroustrup
Online Resources
- cppreference.com
- isocpp.org
- Compiler Explorer (godbolt.org)
- CppCon Conference Videos
Learning Platforms
- Coursera C++ Specialization
- edX C++ Courses
- Udacity C++ Nanodegree
Note: This cheatsheet provides a comprehensive overview of C++. Always refer to the latest language standards and compiler documentation for the most up-to-date information.
Continue Learning
Discover more cheatsheets to boost your productivity