C++ Basics

Variables & Data Types

// Variable declaration and initialization
int x = 5;
float pi = 3.14159;
double precise = 3.1415926535;
char letter = 'A';
bool isActive = true;

// Type modifiers
unsigned int positiveOnly = 100;
short int smallNumber = 10;
long int bigNumber = 1000000;

// Constants
const int MAX_SIZE = 100;
#define PI 3.14159

// Auto keyword (C++11)
auto value = 5; // int
auto name = "C++"; // const char*

// Multiple assignment (C++17)
auto [a, b, c] = std::make_tuple(1, 2, 3);

Basic Operators

// Arithmetic operators
int sum = 5 + 3;
int diff = 10 - 2;
int product = 4 * 5;
int quotient = 15 / 3;
int remainder = 15 % 4;

// Comparison operators
bool isEqual = (x == y);
bool notEqual = (x != y);
bool greater = (x > y);
bool lessOrEqual = (x <= y);

// Logical operators
bool andResult = (x && y);
bool orResult = (x || y);
bool notResult = !x;

// Compound assignment
x += 5;  // x = x + 5
y *= 2;  // y = y * 2

// Increment/Decrement
int preIncrement = ++x;  // increment then use
int postIncrement = x++; // use then increment

// Ternary operator
int max = (a > b) ? a : b;

Control Flow

Conditionals

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

// Switch statement
switch (grade) {
    case 'A':
        std::cout << "Excellent";
        break;
    case 'B':
        std::cout << "Good";
        break;
    case 'C':
        std::cout << "Average";
        break;
    default:
        std::cout << "Invalid grade";
}

// Conditional operator (ternary)
std::cout << (x % 2 == 0 ? "Even" : "Odd");

// Initialization in if (C++17)
if (auto result = calculate(); result > 0) {
    std::cout << "Positive result: " << result;
}

Loops

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

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

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

// Do-while loop
int i = 0;
do {
    std::cout << i << " ";
    i++;
} while (i < 5);

// Loop control
for (int i = 0; i < 10; i++) {
    if (i == 3) continue; // Skip iteration
    if (i == 7) break;    // Exit loop
    std::cout << i << " ";
}

Functions

Basic Functions

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

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

// Default arguments
double calculate(double principal, double rate = 0.05, int time = 1) {
    return principal * rate * time;
}

// Function overloading
int multiply(int a, int b) {
    return a * b;
}

double multiply(double a, double b) {
    return a * b;
}

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

// Pass by reference
void increment(int &x) {
    x++;
}

// Pass by pointer
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

Advanced Functions

// Lambda functions (C++11)
auto square = [](int x) { return x * x; };
auto add = [](int a, int b) -> int { return a + b; };

// Lambda with capture
int multiplier = 3;
auto times = [multiplier](int x) { return x * multiplier; };

// Function pointers
int (*funcPtr)(int, int) = add;

// Recursive functions
int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

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

// Variadic templates (C++11)
template<typename... Args>
void printAll(Args... args) {
    (std::cout << ... << args) << std::endl;
}

// constexpr functions (C++11)
constexpr int squareConstexpr(int x) {
    return x * x;
}

Object-Oriented Programming

Classes & Objects

// Class definition
class Rectangle {
private:
    double width, height;
    
public:
    // Constructor
    Rectangle(double w, double h) : width(w), height(h) {}
    
    // Default constructor
    Rectangle() : width(0), height(0) {}
    
    // Copy constructor
    Rectangle(const Rectangle &other) {
        width = other.width;
        height = other.height;
    }
    
    // Destructor
    ~Rectangle() {
        std::cout << "Rectangle destroyed";
    }
    
    // Member function
    double area() const {
        return width * height;
    }
    
    // Getter
    double getWidth() const { return width; }
    
    // Setter
    void setWidth(double w) { width = w; }
};

// Creating objects
Rectangle rect(5.0, 3.0);
Rectangle rect2; // default constructor
Rectangle rect3 = rect; // copy constructor

// Using objects
double area = rect.area();
rect.setWidth(10.0);

Inheritance & Polymorphism

// Base class
class Shape {
protected:
    std::string color;
    
public:
    Shape(std::string c) : color(c) {}
    
    // Virtual function (runtime polymorphism)
    virtual double area() const = 0; // Pure virtual
    
    // Virtual destructor
    virtual ~Shape() {}
    
    void setColor(std::string c) { color = c; }
    std::string getColor() const { return color; }
};

// Derived class
class Circle : public Shape {
private:
    double radius;
    
public:
    Circle(double r, std::string c) : Shape(c), radius(r) {}
    
    // Override area function
    double area() const override {
        return 3.14159 * radius * radius;
    }
};

// Using inheritance and polymorphism
Shape* shape = new Circle(5.0, "red");
double circleArea = shape->area(); // Calls Circle's area()
delete shape;

// Multiple inheritance
class Drawable {
public:
    virtual void draw() = 0;
};

class DrawableCircle : public Circle, public Drawable {
public:
    DrawableCircle(double r, std::string c) : Circle(r, c) {}
    
    void draw() override {
        std::cout << "Drawing a circle";
    }
};

Operator Overloading

class Vector {
public:
    double x, y;
    
    Vector(double x, double y) : x(x), y(y) {}
    
    // Overload + operator
    Vector operator+(const Vector& other) const {
        return Vector(x + other.x, y + other.y);
    }
    
    // Overload - operator
    Vector operator-(const Vector& other) const {
        return Vector(x - other.x, y - other.y);
    }
    
    // Overload * operator (scalar multiplication)
    Vector operator*(double scalar) const {
        return Vector(x * scalar, y * scalar);
    }
    
    // Overload == operator
    bool operator==(const Vector& other) const {
        return (x == other.x) && (y == other.y);
    }
    
    // Overload << operator for output
    friend std::ostream& operator<<(std::ostream& os, const Vector& v) {
        os << "(" << v.x << ", " << v.y << ")";
        return os;
    }
    
    // Overload [] operator
    double operator[](int index) const {
        if (index == 0) return x;
        if (index == 1) return y;
        throw std::out_of_range("Index out of range");
    }
};

// Using overloaded operators
Vector v1(1.0, 2.0);
Vector v2(3.0, 4.0);
Vector v3 = v1 + v2;
Vector v4 = v1 * 2.0;
bool equal = (v1 == v2);
std::cout << v3; // Outputs: (4.0, 6.0)

Templates

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

// Class template
template <typename T, int N>
class Array {
private:
    T elements[N];
    
public:
    T& operator[](int index) {
        if (index < 0 || index >= N) {
            throw std::out_of_range("Index out of range");
        }
        return elements[index];
    }
    
    int size() const { return N; }
};

// Template specialization
template <>
class Array<bool, 10> {
// Special implementation for bool arrays
};

// Variable templates (C++14)
template<typename T>
constexpr T pi = T(3.1415926535897932385L);

// Using templates
int maxInt = max<int>(5, 10);
double maxDouble = max(3.14, 2.71); // Type deduction

Array<int, 5> intArray;
intArray[0] = 10;

Array3> stringArray;
stringArray[1] = "Hello";

double circleArea = pi<double> * 5 * 5;