Functions & OOP

Progress:

Functions in C++

Functions allow you to group code into reusable blocks. They can take parameters and return values.

Function Example

// Function declaration
int addNumbers(int a, int b) {
    return a + b;
}

// Function call
int result = addNumbers(5, 7);
cout << "Sum: " << result << endl;

Object-Oriented Programming

C++ supports object-oriented programming with classes and objects.

Class Example

class Rectangle {
    private:
        int width, height;
    
    public:
        // Constructor
        Rectangle(int w, int h) {
            width = w;
            height = h;
        }
        
        // Method to calculate area
        int area() {
            return width * height;
        }
};

// Create object and use it
Rectangle rect(3, 4);
cout << "Area: " << rect.area() << endl;

Inheritance Example

class Shape {
    protected:
        int width, height;
    
    public:
        void setDimensions(int w, int h) {
            width = w;
            height = h;
        }
};

class Triangle: public Shape {
    public:
        int area() {
            return (width * height) / 2;
        }
};

Triangle tri;
tri.setDimensions(5, 8);
cout << "Triangle area: " << tri.area() << endl;