logo
eng-flag

C++ Cheatsheet

Table of Contents

  1. Basic Syntax
  2. Data Types
  3. Variables
  4. Operators
  5. Control Flow
  6. Functions
  7. Arrays and Pointers
  8. Object-Oriented Programming
  9. Templates
  10. Standard Template Library (STL)
  11. Exception Handling
  12. File Handling
  13. Memory Management
  14. Preprocessor Directives

Basic Syntax

Comments

// This is a single-line comment

/*
This is a
multi-line comment
*/

Main Function

Every C++ program starts from the main function:

#include <iostream>

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

Data Types

Primitive Data Types

bool b = true;
char c = 'A';
short s = 32767;
int i = 2147483647;
long l = 9223372036854775807L;
float f = 3.14f;
double d = 3.14159265359;

Derived Data Types

int arr[5];  // Array
int* ptr;    // Pointer
int& ref = i;  // Reference

Variables

// Variable declaration
int number;

// Variable initialization
number = 10;

// Declaration and initialization
int age = 25;

// Constants
const double PI = 3.14159;

// Auto keyword
auto x = 5;  // x is deduced to be an int

Operators

Arithmetic Operators

int a = 10, b = 3;

std::cout << a + b << std::endl;  // Addition: 13
std::cout << a - b << std::endl;  // Subtraction: 7
std::cout << a * b << std::endl;  // Multiplication: 30
std::cout << a / b << std::endl;  // Division: 3
std::cout << a % b << std::endl;  // Modulus: 1

Comparison Operators

int x = 5, y = 10;

std::cout << (x == y) << std::endl;  // Equal to: 0 (false)
std::cout << (x != y) << std::endl;  // Not equal to: 1 (true)
std::cout << (x > y) << std::endl;   // Greater than: 0 (false)
std::cout << (x < y) << std::endl;   // Less than: 1 (true)
std::cout << (x >= y) << std::endl;  // Greater than or equal to: 0 (false)
std::cout << (x <= y) << std::endl;  // Less than or equal to: 1 (true)

Logical Operators

bool a = true, b = false;

std::cout << (a && b) << std::endl;  // Logical AND: 0 (false)
std::cout << (a || b) << std::endl;  // Logical OR: 1 (true)
std::cout << (!a) << std::endl;      // Logical NOT: 0 (false)

Control Flow

If-Else Statement

int x = 10;

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

Switch Statement

int day = 3;
switch (day) {
    case 1:
        std::cout << "Monday" << std::endl;
        break;
    case 2:
        std::cout << "Tuesday" << std::endl;
        break;
    case 3:
        std::cout << "Wednesday" << std::endl;
        break;
    default:
        std::cout << "Other day" << std::endl;
}

For Loop

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

// Range-based for loop (C++11)
int numbers[] = {1, 2, 3, 4, 5};
for (int num : numbers) {
    std::cout << num << " ";
}
std::cout << std::endl;

While Loop

int count = 0;
while (count < 5) {
    std::cout << count << " ";
    count++;
}
std::cout << std::endl;

Do-While Loop

int i = 0;
do {
    std::cout << i << " ";
    i++;
} while (i < 5);
std::cout << std::endl;

Functions

// Function declaration
int add(int a, int b);

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

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

// Default arguments
void greet(std::string name = "World") {
    std::cout << "Hello, " << name << "!" << std::endl;
}

// Inline function
inline int square(int x) {
    return x * x;
}

// Lambda function (C++11)
auto multiply = [](int a, int b) { return a * b; };

Arrays and Pointers

// Array declaration and initialization
int numbers[5] = {1, 2, 3, 4, 5};

// Accessing array elements
std::cout << numbers[0] << std::endl;  // Prints 1

// Pointer declaration and initialization
int* ptr = numbers;

// Pointer arithmetic
std::cout << *ptr << std::endl;       // Prints 1
std::cout << *(ptr + 1) << std::endl; // Prints 2

// Dynamic memory allocation
int* dynamicArray = new int[5];
delete[] dynamicArray;

Object-Oriented Programming

Class Definition

class Car {
private:
    std::string brand;
    std::string model;

public:
    // Constructor
    Car(std::string brand, std::string model) : brand(brand), model(model) {}

    // Destructor
    ~Car() {}

    // Member function
    void start() {
        std::cout << "The car is starting..." << std::endl;
    }

    // Getter
    std::string getBrand() const {
        return brand;
    }

    // Setter
    void setBrand(const std::string& newBrand) {
        brand = newBrand;
    }
};

Object Creation and Usage

Car myCar("Toyota", "Corolla");
myCar.start();
std::cout << myCar.getBrand() << std::endl;

Inheritance

class ElectricCar : public Car {
private:
    int batteryCapacity;

public:
    ElectricCar(std::string brand, std::string model, int batteryCapacity)
        : Car(brand, model), batteryCapacity(batteryCapacity) {}

    void start() override {
        std::cout << "The electric car is starting silently..." << std::endl;
    }
};

Templates

// Function template
template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

// Class template
template <typename T>
class Box {
private:
    T content;

public:
    void setContent(T content) {
        this->content = content;
    }

    T getContent() {
        return content;
    }
};

Standard Template Library (STL)

Vectors

#include <vector>

std::vector<int> numbers = {1, 2, 3, 4, 5};
numbers.push_back(6);
std::cout << numbers[0] << std::endl;  // Prints 1
std::cout << numbers.size() << std::endl;  // Prints 6

Maps

#include <map>

std::map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
std::cout << ages["Alice"] << std::endl;  // Prints 30

Algorithms

#include <algorithm>

std::vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5};
std::sort(numbers.begin(), numbers.end());
auto it = std::find(numbers.begin(), numbers.end(), 5);

Exception Handling

#include <stdexcept>

try {
    int result = 10 / 0;
} catch (const std::exception& e) {
    std::cerr << "Exception caught: " << e.what() << std::endl;
} catch (...) {
    std::cerr << "Unknown exception caught" << std::endl;
}

// Throwing an exception
void checkAge(int age) {
    if (age < 0) {
        throw std::invalid_argument("Age cannot be negative");
    }
}

File Handling

#include <fstream>

// Writing to a file
std::ofstream outFile("output.txt");
outFile << "Hello, World!" << std::endl;
outFile.close();

// Reading from a file
std::ifstream inFile("input.txt");
std::string line;
while (std::getline(inFile, line)) {
    std::cout << line << std::endl;
}
inFile.close();

Memory Management

// Dynamic memory allocation
int* ptr = new int;
*ptr = 10;
delete ptr;

// Dynamic array allocation
int* arr = new int[5];
delete[] arr;

// Smart pointers (C++11)
#include <memory>

std::unique_ptr<int> uniquePtr = std::make_unique<int>(42);
std::shared_ptr<int> sharedPtr = std::make_shared<int>(42);

Preprocessor Directives

#define PI 3.14159
#define SQUARE(x) ((x) * (x))

#ifdef DEBUG
    std::cout << "Debug mode is on" << std::endl;
#endif

#ifndef MY_HEADER_H
#define MY_HEADER_H
// Header file contents
#endif

2024 © All rights reserved - buraxta.com