Overloading Binary Operators
A binary operator works with two operands.
Examples:
a + ba - ba == ba < b
Why Member Binary Operators Take One Parameter
This is a very common viva question.
When a binary operator is overloaded as a member function, the left operand is the calling object.
c1 + c2
is treated like:
c1.operator+(c2);
So only the right operand is passed as an explicit parameter.
Complete Member Function Example
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
bool operator==(const Complex& other) const {
return real == other.real && imag == other.imag;
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex a(2, 3);
Complex b(4, 5);
Complex c = a + b;
c.display();
cout << boolalpha << (a == b) << endl;
return 0;
}
Output:
6 + 8i
false
Non-Member Binary Operator
When a binary operator is overloaded as a non-member function, both operands are passed explicitly.
operator+(a, b);
That means it takes two parameters.
#include <iostream>
using namespace std;
class Money {
private:
int taka;
public:
Money(int amount = 0) : taka(amount) {}
friend Money operator+(const Money& left, const Money& right) {
return Money(left.taka + right.taka);
}
void display() const {
cout << taka << " taka" << endl;
}
};
int main() {
Money m1(100);
Money m2(50);
Money total = m1 + m2;
total.display();
return 0;
}
Member vs Friend
Use a member function when the left operand is naturally the object.
object + other
Use a non-member or friend function when the left operand is not your class, or when you want symmetric behavior.
Example:
5 + money
Here 5 cannot call a Money member function. A non-member operator may be needed.
Can Function Overloading Replace Operator Overloading?
Yes, sometimes.
Instead of:
Money total = m1 + m2;
you can write:
Money total = m1.add(m2);
The logic can be the same. But operator overloading gives natural syntax when the operation is obvious.
Viva Answer
For a member binary operator, only one parameter is passed because the left operand is the calling object and the right operand is the explicit argument. For a non-member binary operator, both operands must be passed as parameters.
Quick Check
- In
a + b, which object calls a memberoperator+? - Why does a member binary operator take one parameter?
- Why might
5 + objrequire a non-member operator?