⚡ C++ Programming
C++ Complete Cheatsheet
Pointers, OOP, STL, templates, smart pointers — complete modern C++ reference.
01
Basics & Types
▼
CPPC++ basics
#include#include using namespace std; int main() { // Variables int age = 22; double pi = 3.14159; char grade = 'A'; bool active = true; string name = "Ali"; auto x = 42; // type deduction (C++11) // I/O cout << "Hello " << name << endl; cin >> age; cout << "Age: " << age << "\n"; // Constants const int MAX = 100; constexpr double PI = 3.14159; // compile-time constant // Casting double d = 7.9; int i = static_cast (d); // 7 (C++ style cast) return 0; }
CPPControl flow
// Range-based for (C++11)
for (int x : {1, 2, 3}) { cout << x; }
for (auto& item : collection) { /* use item */ }
// switch with enum
switch(day) {
case 1: cout << "Mon"; break;
case 2: cout << "Tue"; break;
default: cout << "Other";
}
int
32-bit signed integer
long long
64-bit integer — use for large numbers
size_t
Unsigned type for sizes and indices
auto
Type deduction — compiler infers type
02
Functions
▼
CPPFunctions
// Value vs reference vs const reference
void byValue(int x) { x = 10; } // copy — x unchanged outside
void byRef(int& x) { x = 10; } // modifies original
void byConstRef(const string& s) { // read-only, no copy
cout << s;
}
// Return multiple values
pair minmax(vector& v) {
return {*min_element(v.begin(), v.end()),
*max_element(v.begin(), v.end())};
}
auto [lo, hi] = minmax(v); // structured bindings (C++17)
// Default parameters
void log(string msg, string level = "INFO") {
cout << "[" << level << "] " << msg;
}
// Function overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
// Lambda (C++11)
auto square = [](int x) { return x * x; };
auto adder = [](int n) { return [n](int x) { return x + n; }; };
💡
Pass large objects by const reference (const string&) to avoid copying while preventing modification.
03
Pointers & References
▼
CPPPointers and references
int x = 42;
int* p = &x; // pointer to x
int& r = x; // reference to x
cout << *p; // dereference: 42
cout << &x; // address of x
*p = 100; // modifies x through pointer
r = 100; // modifies x through reference
// nullptr (C++11 — use instead of NULL or 0)
int* ptr = nullptr;
if (ptr != nullptr) { /* ... */ }
// Pointer arithmetic
int arr[] = {1, 2, 3, 4, 5};
int* p2 = arr; // points to arr[0]
p2++; // now points to arr[1]
*(p2 + 2) == arr[3]; // true
// Const with pointers
const int* p3 = &x; // can't change value via pointer
int* const p4 = &x; // can't change what pointer points to
const int* const p5 = &x; // both const
Pointer
Stores memory address. Can be null, can change what it points to.
Reference
Alias for existing variable. Must be initialized. Can't be null or reassigned.
Smart pointers
unique_ptr, shared_ptr — manage memory automatically (C++11)
04
OOP Classes
▼
CPPClasses
class Student {
private: // only accessible within class
string name;
int grade;
static int count; // shared across all instances
public:
// Constructor
Student(string n, int g) : name(n), grade(g) {
count++;
}
// Destructor
~Student() { count--; }
// Getters (const method — doesn't modify)
string getName() const { return name; }
int getGrade() const { return grade; }
// Setter
void setGrade(int g) {
if (g >= 0 && g <= 100) grade = g;
}
// Static method
static int getCount() { return count; }
// Operator overload
bool operator<(const Student& other) const {
return grade < other.grade;
}
};
int Student::count = 0; // static member definition
Student s("Ali", 95);
cout << Student::getCount(); // 1
05
Inheritance
▼
CPPInheritance and polymorphism
class Shape {
public:
virtual double area() const = 0; // pure virtual = abstract
virtual string name() const { return "Shape"; } // virtual
virtual ~Shape() {} // virtual destructor (essential!)
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
string name() const override { return "Circle"; }
};
class Rectangle : public Shape {
double w, h;
public:
Rectangle(double w, double h) : w(w), h(h) {}
double area() const override { return w * h; }
};
// Polymorphism via pointer/reference
vector> shapes;
shapes.push_back(make_unique(5.0));
shapes.push_back(make_unique(4.0, 6.0));
for (auto& s : shapes) {
cout << s->name() << ": " << s->area() << "\n";
}
⚠️
Always make destructors virtual in base classes. Without it, deleting via base pointer causes undefined behaviour.
06
STL Containers
▼
CPPSTL Containers
#include#include
vector
Prefer for sequential data. Random access O(1). Append O(1) amortized.
map vs unordered_map
map: sorted, O(log n). unordered_map: O(1) avg, no ordering.
priority_queue
Max-heap by default. Use for greedy algorithms.
07
STL Algorithms
▼
CPPSTL Algorithms
#include#include vector v = {3, 1, 4, 1, 5, 9, 2, 6}; // Sort sort(v.begin(), v.end()); // ascending sort(v.begin(), v.end(), greater ()); // descending sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); // Search auto it = find(v.begin(), v.end(), 5); // linear search bool found = binary_search(v.begin(), v.end(), 5); // sorted! // Transform transform(v.begin(), v.end(), v.begin(), [](int x) { return x*2; }); // Reduce int sum = accumulate(v.begin(), v.end(), 0); int product = accumulate(v.begin(), v.end(), 1, multiplies ()); // Count int cnt = count(v.begin(), v.end(), 1); int cnt_if = count_if(v.begin(), v.end(), [](int x) { return x > 3; }); // Min/Max auto [lo, hi] = minmax_element(v.begin(), v.end()); // Reverse, shuffle, unique reverse(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); // remove consecutive dups
08
Memory Management
▼
CPPModern memory management
// Prefer smart pointers over raw pointers! #include// unique_ptr: single owner, automatic delete ruto ptr = make_unique ("Ali", 95); ptr->getName(); // access like pointer // auto ptr2 = ptr; // ERROR: can't copy auto ptr2 = move(ptr); // transfer ownership // shared_ptr: reference counted, multiple owners auto sp1 = make_shared ("Ali", 95); auto sp2 = sp1; // both point to same Student sp1.use_count(); // 2 // deleted when count reaches 0 // weak_ptr: observe without owning (break cycles) weak_ptr wp = sp1; if (auto locked = wp.lock()) { locked->getName(); // safe: only if still alive } // RAII: resource allocated in constructor, freed in destructor // Rule of Five (modern C++): // If you define any of these, define all 5: // destructor, copy ctor, copy assign, move ctor, move assign
💡
Use make_unique and make_shared instead of new/delete. Smart pointers eliminate memory leaks and dangling pointers.
09
Templates
▼
CPPTemplates
// Function template templateT max(T a, T b) { return (a > b) ? a : b; } max(3, 5); // int max(3.14, 2.71); // double // Class template template class Array { T data[N]; public: T& operator[](int i) { return data[i]; } int size() const { return N; } }; Array arr; arr[0] = 42; // Variadic templates (C++11) template void print(Args... args) { (cout << ... << args) << endl; // fold expression C++17 } print(1, 2.5, "hello"); // prints: 12.5hello // Template specialization template<> string max (string a, string b) { return (a.length() > b.length()) ? a : b; }
SFINAE
Substitution Failure Is Not An Error — enables template metaprogramming
auto
C++14: return type deduction. Use for complex iterator types.
Concepts (C++20)
constrain templates: template void fn(T x)
10
Mini Quizzes
▼
❓ Quiz 1
What is the difference between a pointer and a reference in C++?
Reference: alias for existing variable, must be initialized, can't be null, can't be reassigned. Pointer: stores memory address, can be null (nullptr), can point to different objects.
❓ Quiz 2
Why should base class destructors be virtual?
Without virtual destructor, deleting a derived object through a base pointer calls only the base destructor — causing a resource leak (the derived part isn't cleaned up). Always make base destructors virtual!