GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR
← Back to All Lessons
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }

cout << add(2, 3) << endl;       // 5 (int version)
cout << add(2.5, 3.1) << endl;   // 5.6 (double version)
cout << add(1, 2, 3) << endl;    // 6 (3-arg version)

Operator Overloading

class Vector {
public:
    double x, y;
    Vector(double x, double y) : x(x), y(y) {}

    // Overload + operator
    Vector operator+(const Vector& v) {
        return Vector(x + v.x, y + v.y);
    }

    void print() { cout << "(" << x << ", " << y << ")" << endl; }
};

Vector a(1, 2), b(3, 4);
Vector c = a + b;  // Uses our + operator!
c.print();         // (4, 6)

Virtual Functions (Runtime Polymorphism)

class Shape {
public:
    virtual double area() { return 0; }  // virtual!
    virtual ~Shape() {}
};

class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() override { return 3.14159 * r * r; }
};

class Rectangle : public Shape {
    double w, h;
public:
    Rectangle(double w, double h) : w(w), h(h) {}
    double area() override { return w * h; }
};

// Polymorphism in action!
Shape* shapes[] = { new Circle(5), new Rectangle(4, 6) };
for (auto s : shapes) {
    cout << "Area: " << s->area() << endl;
    delete s;
}
// Output: Area: 78.5398  Area: 24

✅ Quick Quiz

❓ What keyword enables runtime polymorphism?

❓ What is function overloading?

❓ What does 'override' keyword indicate?

← Previous Next: Templates →