C++ Operator Overloading

Operator overloading in C++ allows you to redefine the behavior of operators (like +, -, *, etc.) for user-defined types such as classes. This helps make objects of your class work similarly to built-in types and makes the code more intuitive and readable.

Rules for Operator Overloading

  • Operator overloading increases code readability and allows objects to behave like built-in types.
  • Operators can be overloaded as member functions or friend functions.
  • Always maintain intuitive behavior for overloaded operators to avoid confusing code.

Next Topic

Next, learn about Type Casting in C++.

  • You cannot create new operators; you can only overload existing ones.
  • At least one operand must be a user-defined type.
  • Certain operators like ::, sizeof, ., .*, and ? cannot be overloaded.

Syntax

ReturnType operatorSymbol(ParameterList) {
    // Implementation of the operator
}

Example: Overloading + Operator

#include <iostream>
using namespace std;

class Point {
private:
    int x, y;

public:
    Point(int x1 = 0, int y1 = 0) : x(x1), y(y1) {}

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

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

int main() {
    Point p1(2, 3), p2(4, 5);
    Point p3 = p1 + p2; // Calls overloaded + operator

    cout << "Point p3: ";
    p3.display();

    return 0;
}

Output

(6, 8)

Example: Overloading << Operator for Output

#include <iostream>
using namespace std;

class Point {
private:
    int x, y;

public:
    Point(int x1 = 0, int y1 = 0) : x(x1), y(y1) {}

    // Overload << operator
    friend ostream& operator<<(ostream &out, const Point &p) {
        out << "(" << p.x << ", " << p.y << ")";
        return out;
    }
};

int main() {
    Point p1(3, 7);
    cout << "Point: " << p1 << endl;
    return 0;
}

Output

Point: (3, 7)

Important Notes

  • Operator overloading increases code readability and allows objects to behave like built-in types.
  • Operators can be overloaded as member functions or friend functions.
  • Always maintain intuitive behavior for overloaded operators to avoid confusing code.

Next Topic

Next, learn about Type Casting in C++.