- 2070 Asar · 4 marks
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;
}
| Point | Unary | Binary |
|---|---|---|
| Operands | One | Two |
| Member function arguments | None | One |
| Friend function arguments | One | Two |
| Examples | -a, ++a, !a | a + b, a == b |
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Syntax of operator overloading · Object Oriented Programming, chapter 5 · asked 4×
- City class with operator overloading · Object Oriented Programming, chapter 5
- Binary operator member function one argument · Object Oriented Programming, chapter 5
- Operator overloading: need and definition · Object Oriented Programming, chapter 5 · asked 3×
- Disadvantage of operator overloading · Object Oriented Programming, chapter 5
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3
- Operators; conditional operator · Computer Programming, chapter 3