Binary Operator
⭐ What is a Binary Operator?
A binary operator is an operator that works on two operands.
Example:
a + b
x - y
p * q
Here +, -, *, /, %, <, > etc. are binary operators because they need two values.
⭐ What is Binary Operator Overloading?
Binary operator overloading means:
Giving a new meaning to a binary operator when it is used with objects of a class.
Example:
c3 = c1 + c2;
Here c1 and c2 are objects.
The compiler doesn't know how to add them.
So we overload the + operator to teach the compiler what to do.
⭐ Why do we overload binary operators?
Because operators like +, -, * know how to work on int, float, etc.,
but they don't know how to work on your custom objects.
So you tell the compiler:
"When I use + between two objects of this class, run this function."
⭐ Syntax of Binary Operator Overloading
returnType operator+(ClassName obj) {
// Your logic
}
This function runs when you write:
obj3 = obj1 + obj2;
⭐ Easy Real-Life Example (Time Addition)
Let’s add hours and minutes using the + operator.
#include <iostream>
using namespace std;
class Time {
public:
int hr, min;
Time(int h = 0, int m = 0) {
hr = h;
min = m;
}
// binary operator overloading
Time operator+(Time t) {
Time temp;
temp.hr = hr + t.hr;
temp.min = min + t.min;
if (temp.min >= 60) {
temp.hr += temp.min / 60;
temp.min = temp.min % 60;
}
return temp;
}
void display() {
cout << hr << " hours " << min << " minutes" << endl;
}
};
int main() {
Time t1(2, 50);
Time t2(1, 30);
Time t3 = t1 + t2; // operator+() called
t3.display();
return 0;
}
⭐ Output
4 hours 20 minutes
⭐ Quick Summary (Very Easy)
Binary operator → works on 2 operands
Example: +, -, *, /, %, <, >
Overloading means → giving new meaning for objects
You write
operator+inside the classWhen you use
obj1 + obj2, your overloaded function runs.