⬅ Previous Next ➡

Operator Overloading

Operator Overloading in C++
  • Operator Overloading allows you to define how operators (+, -, ++, ==, etc.) work with user-defined types (classes).
  • It improves readability: objects can behave like built-in types.
  • Operators can be overloaded using member functions or friend functions.

1) Unary Operator Overloading (Example: ++)

  • Unary operator works on one operand (++, --, -).
  • Pre-increment overload syntax: Type operator++()
#include <iostream>
using namespace std;

class Counter {
    int value;

public:
    Counter(int v = 0) { value = v; }

    void show() {
        cout << "Value = " << value << endl;
    }

    // Unary ++ (pre-increment)
    void operator++() {
        value++;
    }
};

int main() {
    Counter c(5);
    ++c;
    c.show();
    return 0;
}

2) Binary Operator Overloading (Example: +)

  • Binary operator works on two operands (+, -, *, /, ==).
  • Overload + to add two objects.
#include <iostream>
using namespace std;

class Point {
public:
    int x, y;

    Point(int a = 0, int b = 0) {
        x = a;
        y = b;
    }

    Point operator + (const Point &p) {
        return Point(x + p.x, y + p.y);
    }

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

int main() {
    Point p1(2, 3), p2(4, 1);
    Point p3 = p1 + p2;

    p3.show();
    return 0;
}

3) Friend Function in Operator Overloading

  • friend function can access private members of a class.
  • Used when left operand is not an object of the class (e.g., int + Object).
3.1) Friend Function Example (overload +)
#include <iostream>
using namespace std;

class Box {
    int length;

public:
    Box(int l = 0) { length = l; }

    friend Box operator + (Box b1, Box b2);

    void show() {
        cout << "Length = " << length << endl;
    }
};

Box operator + (Box b1, Box b2) {
    return Box(b1.length + b2.length);
}

int main() {
    Box b1(10), b2(20);
    Box b3 = b1 + b2;

    b3.show();
    return 0;
}

4) Rules and Limitations of Operator Overloading

  • Only existing operators can be overloaded (cannot create new operator symbols).
  • At least one operand must be a user-defined type (class/struct).
  • Operator precedence and associativity cannot be changed.
  • Some operators cannot be overloaded:
    • :: (scope resolution)
    • . (member access)
    • .* (pointer to member)
    • ?: (ternary)
    • sizeof
    • typeid
  • Operators that must be overloaded as member functions:
    • =, (), [], ->

5) Quick Notes

  • Unary overloading: one operand (++, --).
  • Binary overloading: two operands (+, -, ==).
  • Use friend when you need access to private members or for left operand cases.
  • Keep operator overloading meaningful (avoid confusing behavior).
⬅ Previous Next ➡