Skip to main content

Binary and unary operator overloading

Short answer

Unary overload: member takes no argument (operand is this), friend takes one. E.g., void operator-() negates. Binary overload: member takes one argument (right operand), friend takes two. E.g., Point operator+(Point) adds. Syntax: member – ret_type operator op(); friend – ret_type operator op(arg).

Explain the binary and unary operator overloading along with their syntax and example.

Unary operator overloading

A unary operator works on a single operand (e.g. -, ++, --, !). As a member function it takes no argument, because the operand is the calling object. As a friend function it takes one argument.

Syntax:

return_type operator op ();                 // member
friend return_type operator op (Class &a);  // friend

Example - unary minus (negates a point):

#include <iostream>
using namespace std;

class Point {
    int x, y;
public:
    Point(int a = 0, int b = 0) { x = a; y = b; }
    void operator-() { x = -x; y = -y; }     // unary minus
    void show() { cout << "(" << x << ", " << y << ")" << endl; }
};

int main() {
    Point p(3, -4);
    -p;                  // calls p.operator-()
    p.show();            // (-3, 4)
    return 0;
}

Binary operator overloading

A binary operator works on two operands (e.g. +, -, *, ==). As a member function it takes one argument (the right operand; the left is the calling object). As a friend it takes two arguments.

Syntax:

return_type operator op (Class b);                 // member
friend return_type operator op (Class a, Class b); // friend

Example - adding two points:

#include <iostream>
using namespace std;

class Point {
    int x, y;
public:
    Point(int a = 0, int b = 0) { x = a; y = b; }
    Point operator+(Point p) {                // binary +
        return Point(x + p.x, y + p.y);
    }
    void show() { cout << "(" << x << ", " << y << ")" << endl; }
};

int main() {
    Point a(1, 2), b(3, 4), c;
    c = a + b;           // a.operator+(b)
    c.show();            // (4, 6)
    return 0;
}
PointUnaryBinary
OperandsOneTwo
Member function argumentsNoneOne
Friend function argumentsOneTwo
Examples-a, ++a, !aa + b, a == b

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →