⬅ Back

C++ Programming Cheatsheet

Basic Structure

#include <iostream> using namespace std; int main() { cout << "Hello, World!"; return 0; }

Preprocessor

Variables

Declaration:
int age;
Initialization:
char grade = 'A';

cout & cin

Data Types & Ranges

Operators

Type Conversion

Implicit: Low → High, safe
int a = 5; float b = a;
Explicit (Casting): High → Low, may lose data
int a = (int)5.5;

Control Structures

Functions

Declaration:
int add(int, int);
Call:
sum = add(5, 3);
Supports call by value & call by reference.

Types of Functions

References

Provides an alias for existing variables int var = 12; int& ref = var; //Reference

Vectors

Dynamic arrays from STL #include <vector> vector<datatype> vector_name;
Commonly used Vector Functions are push_back(), pop_back(), at(i), size(), clear()

Automatically resizes when modified

Pointers

Stores memory address of another variable.
int x = 10;
int *ptr = &x;
*ptr = 20;

*ptr gets the value at x.

Arrays

Collection of same-type elements.
1D: int a[3] = {10, 20, 30};
2D: int b[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

Strings

Array of characters ending with `\0`.
string name[] = "Imad";
use <string> class for string functions like length(), append(), substr().

String I/O Functions

Structures

Collection of different data types. Each member has its own memory location.
struct Student { int id; string name; }; struct Student s1; s1.id = 101;

Unions

Collection of different data types in the same memory location. Only one member can hold a value at any given time. union Data { int i; char str[20]; };

Typedef

Creates an alias for a data type.
typedef struct { int id; char name[20]; } Student;
Student s1;

Enum

Assigns names to integer constants.
enum Day {SUN, MON}; enum Day d = MON;
Note: Sturcture, Union and Enum are user-defined data types.

Classes & Objects

Classes are blueprint for creating objects.
class MyClass { public: void display() { cout << "Hello"; } }; MyClass obj; obj.display();

OOP Concepts

File Basics

#include <fstream> int main() { // Create and open file ofstream MyFile("f.txt"); // Write to the file MyFile <<"Hello! world"; // Close the file MyFile.close(); }

File Operations

#include <fstream> ofstream outFile("f.txt");

File Modes

fstream file; file.open("f.txt",ios::out);

Exception Handling

Handles runtime errors gracefully without stopping program execution.
try{ //code to try throw exception; } catch(){ //code to handle errors }

Recursion

A function that calls itself.
return_type func(params) { if (base_case) return value; else return func(new_params); }
⬆ Back to Top