Skip to content

Overloading of Unary and Binary operators

๐Ÿ”„ What is Operator Overloading?

In C++, operator overloading allows you to define or change the behavior of operators (like +, -, ++, ==) for user-defined types (classes).

Operators can be overloaded as:

  • Unary operators: Operate on a single operand (e.g., ++, --, -)
  • Binary operators: Operate on two operands (e.g., +, -, *, /)

๐Ÿ”น Overloading Unary Operators

โœ… Definition:

Unary operators take one operand and can be prefix or postfix.

โœ๏ธ Syntax (as member function):

return_type operator op();

๐Ÿงช Example: Overloading Unary - Operator

#include <iostream>
using namespace std;

class Number {
private:
int value;

public:
Number(int v) : value(v) {}

void operator - () { // Overloading unary minus
value = -value;
}

void display() {
cout << "Value: " << value << endl;
}
};

int main() {
Number n(5);
-n; // Unary minus
n.display(); // Output: -5
return 0;
}

๐Ÿ”ธ Overloading Binary Operators

โœ… Definition:

Binary operators work with two operands (like +, -, *, ==).

โœ๏ธ Syntax (as member function):

return_type operator op (const ClassName &obj);

๐Ÿงช Example: Overloading + Operator

#include <iostream>
using namespace std;

class Point {
private:
int x, y;

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

// 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 +
p3.display(); // Output: (6, 8)
return 0;
}

๐Ÿ“œ Rules for Operator Overloading in C++

  1. Only existing operators can be overloaded (not new ones).
  2. Some operators cannot be overloaded:
    • :: (scope resolution)
    • . (member access)
    • .* (pointer-to-member)
    • sizeof, typeid, ?:, const_cast, etc.
  3. Operator overloading must preserve the number of operands.
    • Unary โ†’ one operand
    • Binary โ†’ two operands
  4. At least one operand must be a user-defined type (class object).
  5. Cannot change precedence or associativity of an operator.
  6. Overloaded operators can be:
    • Member functions (usually preferred)
    • Friend functions (when the left operand is not a class object)

๐Ÿ” Summary Table

Operator TypeExampleOverloaded Function
Unary-noperator-()
Binarya + boperator+(const Obj &b)

โœ… Benefits of Overloading

  • Makes class objects behave like primitive types
  • Improves readability and natural syntax
  • Allows intuitive expressions using user-defined data types