C++ Cheat Sheet

Basics & Syntax

A basic C++ program includes headers, uses the standard namespace, and defines the main function as the entry point.

#include <iostream>
using namespace std;

int main() {
  cout << "Hello, World!" << endl;
  return 0;
}

Data Types

int a = 10;
float b = 5.5;
double c = 3.14;
char d = 'A';
bool e = true;

Variables & Constants

int age = 30;
const float PI = 3.1415;

Input/Output (cin, cout)

int x;
cout << "Enter a number: ";
cin >> x;
cout << "You entered: " << x;

Operators (Arithmetic, Logical, Bitwise, etc.)

Arithmetic operators perform basic mathematical operations:

int a = 10, b = 3;
int sum = a + b;
int diff = a - b;
int prod = a * b;
int quot = a / b;
int mod = a % b;

Relational operators compare two values and return a boolean result:

bool eq = (a == b);
bool neq = (a != b);
bool gt = (a > b);
bool lt = (a < b);
bool ge = (a >= b);
bool le = (a <= b);

Logical operators are used to combine or invert boolean expressions:

bool and_op = (a > 0) && (b < 5);
bool or_op = (a > 0) || (b < 0);
bool not_op = !(a == b);

Bitwise operators operate on individual bits of integer types:

int and_bit = a & b;
int or_bit = a | b;
int xor_bit = a ^ b;
int not_bit = ~a;
int left_shift = a << 1;
int right_shift = a >> 1;

Assignment operators assign and update values:

int x = 5;
x += 3;
x -= 2;
x *= 4;
x /= 2;
x %= 3;

Increment and decrement operators increase or decrease a value by 1:

int i = 0;
i++;
++i;
i--;
--i;

Conditional (ternary) operator provides shorthand for if-else:

int max = (a > b) ? a : b;

Scope resolution operator accesses global or class members:

::std::cout << "Hello";

Pointer and reference operators access memory and refer to variables:

int y = 10;
int* ptr = &y;
int& ref = y;
std::cout << *ptr << " " << ref;

Control Flow (if, else, switch)

Simple if condition:

int x = 5;
if (x > 0) {
  std::cout << "x is positive";
}

if-else condition:

int x = -3;
if (x >= 0) {
  std::cout << "x is non-negative";
} else {
  std::cout << "x is negative";
}

if-else if-else chain for multiple conditions:

int x = 0;
if (x > 0) {
  std::cout << "Positive";
} else if (x == 0) {
  std::cout << "Zero";
} else {
  std::cout << "Negative";
}

switch statement for handling multiple discrete values:

int x = 2;
switch (x) {
  case 1:
    std::cout << "One";
    break;
  case 2:
    std::cout << "Two";
    break;
  default:
    std::cout << "Other";
}

Loops (for, while, do-while)

for (int i = 0; i < 5; i++) {
  cout << i << " ";
}

int j = 0;
while (j < 5) {
  cout << j++ << " ";
}

do {
  cout << j-- << " ";
} while (j > 0);

Functions

int add(int a, int b) {
  return a + b;
}

Function Overloading

Function overloading allows multiple functions with the same name but different parameter types or counts.

int add(int a, int b) {
  return a + b;
}

double add(double a, double b) {
  return a + b;
}

Default Arguments

void greet(string name = "Guest") {
  cout << "Hello, " << name << endl;
}

Recursion

int factorial(int n) {
  if (n == 0) return 1;
  return n * factorial(n - 1);
}

Pointers

Basic pointer usage for storing and accessing the address of a variable:

int x = 10;
int* ptr = &x;
cout << *ptr; // Output: 10

References

A reference is an alias for an existing variable. Changing the reference updates the original value.

int x = 5;
int& ref = x;
ref = 10;
cout << x; // prints 10

Arrays

Declare and initialize a fixed-size array:

int arr[3] = {1, 2, 3};

Access elements using indexing:

cout << arr[0];

Iterate through array elements using a for loop:

for (int i = 0; i < 3; i++) {
  cout << arr[i] << " ";
}

Update a value in the array:

arr[1] = 10;

Calculate the size of an array:

int size = sizeof(arr) / sizeof(arr[0]);
cout << "Size: " << size;

Initialize all elements with zeros:

int arr[5] = {0};

Use range-based for loop (C++11+):

for (int x : arr) {
  cout << x << " ";
}

Strings (C-style and std::string)

C-style string initialization and output:

#include <cstdio>

char name[] = "C-style";
printf("%s
", name);

Initializing and printing a std::string:

#include <iostream>
#include <string>
using namespace std;

string modern = "C++ string";
cout << modern << endl;

Getting the length of a std::string:

cout << modern.length() << endl;

Concatenating two strings:

string first = "Hello, ";
string second = "world!";
string result = first + second;
cout << result << endl;

Accessing characters in a string:

string word = "example";
cout << word[0] << " " << word.at(1) << endl;

Substring extraction:

string text = "abcdef";
string sub = text.substr(1, 3);  // "bcd"
cout << sub << endl;

Finding a substring:

string text = "find the word";
size_t pos = text.find("word");
cout << pos << endl;

Comparing strings:

string a = "apple";
string b = "banana";
if (a < b) {
  cout << "apple comes first" << endl;
}

Converting between C-style and std::string:

string str = "sample";
const char* cstr = str.c_str();

Structures (struct)

Structures allow grouping of different data types into a single unit.

struct Person {
  std::string name;
  int age;
};

Person p = {"Alice", 30};
std::cout << p.name << " is " << p.age << " years old.";

Unions

A union is a user-defined type where all members share the same memory location. Only one member can hold a value at any given time.

union Data {
  int i;
  float f;
};

int main() {
  Data d;
  d.i = 10;
  printf("d.i = %d
", d.i);
  return 0;
}

Enumerations (enum)

Enums define a set of named integer constants for better code readability and maintainability:

enum Color { RED, GREEN, BLUE };
Color c = GREEN;

Dynamic Memory (new, delete)

Allocate and deallocate a single integer using new and delete:

int* p = new int;
*p = 100;
delete p;

Allocate and deallocate a dynamic array using new[] and delete[]:

int* arr = new int[5];
arr[0] = 10;
delete[] arr;

Classes and Objects

class Animal {
public:
  void speak() {
    cout << "Sound";
  }
};

Animal a;
a.speak();

Constructors and Destructors

class MyClass {
public:
  MyClass() {
    cout << "Constructor";
  }
  ~MyClass() {
    cout << "Destructor";
  }
};

Access Specifiers (public, private, protected)

class Test {
private:
  int secret;
public:
  void set(int s) { secret = s; }
};

Inheritance

class Animal {
public:
  void speak() { cout << "Animal"; }
};

class Dog : public Animal {};

Polymorphism (Virtual Functions, Override)

class Base {
public:
  virtual void show() { cout << "Base"; }
};

class Derived : public Base {
public:
  void show() override { cout << "Derived"; }
};

Abstract Classes & Interfaces

class Shape {
public:
  virtual void draw() = 0; // pure virtual
};

Operator Overloading

class Complex {
  int real, imag;
public:
  Complex(int r, int i) : real(r), imag(i) {}
  Complex operator + (const Complex& obj) {
    return Complex(real + obj.real, imag + obj.imag);
  }
};

Friend Functions and Classes

class Box {
  int width;
  friend void printWidth(Box);
};

Namespaces

namespace ns {
  void func() { cout << "Namespace"; }
}

ns::func();

Exception Handling (try, catch, throw)

try {
  throw 20;
} catch (int e) {
  cout << "Exception: " << e;
}

STL (Standard Template Library)

Includes containers, algorithms, and iterators. Examples: vector, map, set, queue, stack.

STL: Vectors

#include <vector>
vector<int> v = {1, 2, 3};
v.push_back(4);
for (int x : v) cout << x << " ";

STL: Maps & Unordered Maps

#include <map>
map<string, int> m;
m["age"] = 30;
cout << m["age"];

STL: Sets & Unordered Sets

#include <set>
set<int> s;
s.insert(1);
s.insert(2);
for (int x : s) cout << x;

STL: Queues, Stacks, Deques

#include <queue>
queue<int> q;
q.push(10);
q.pop();

STL: Algorithms (sort, find, etc.)

#include <algorithm>
vector<int> v = {3, 1, 2};
sort(v.begin(), v.end());

Templates (Function & Class Templates)

template <typename T>
T add(T a, T b) {
  return a + b;
}

Lambda Functions

auto sum = [](int a, int b) { return a + b; };
cout << sum(3, 4);

File I/O (ifstream, ofstream, fstream)

#include <fstream>
ofstream out("file.txt");
out << "Hello";
out.close();

Type Casting (static_cast, dynamic_cast, etc.)

double d = 3.5;
int i = static_cast<int>(d);

Preprocessor Directives (#define, #include, etc.)

#define PI 3.14
#include <iostream>

Const & Mutable

class Example {
  mutable int x;
public:
  void set(int val) const {
    x = val; // allowed
  }
};

Inline Functions

inline int square(int x) {
  return x * x;
}

Smart Pointers (unique_ptr, shared_ptr, weak_ptr)

#include <memory>
auto ptr = std::make_shared<int>(10);

Move Semantics & Rvalue References

vector<int> a = {1, 2};
vector<int> b = std::move(a);

C++11/C++14/C++17/C++20 Features Overview

  • C++11: auto, nullptr, lambda, range-for, smart pointers
  • C++14: binary literals, generic lambdas
  • C++17: if constexpr, structured bindings
  • C++20: concepts, ranges, coroutines