OOP: POLYMORPHISM
Operator Overloading: Compile-time Polymorphism
Operator overloading gives an existing operator a meaning for user-defined types.
Example:
Money total = m1 + m2;
The compiler translates the operator syntax into an operator function call.
Why It Is Compile-time Polymorphism
When the compiler sees:
m1 + m2
it selects a matching operator+ function during compilation.
For a member operator, the call is like:
m1.operator+(m2);
For a non-member operator, the call is like:
operator+(m1, m2);
Complete Example
#include <iostream>
using namespace std;
class Money {
private:
int amount;
public:
Money(int value = 0) : amount(value) {}
Money operator+(const Money& other) const {
return Money(amount + other.amount);
}
bool operator==(const Money& other) const {
return amount == other.amount;
}
void display() const {
cout << amount << " taka" << endl;
}
};
int main() {
Money m1(100);
Money m2(50);
Money total = m1 + m2;
total.display();
cout << boolalpha << (m1 == m2) << endl;
return 0;
}
Output:
150 taka
false
Can Normal Function Overloading Replace It?
Sometimes, yes.
Instead of:
Money total = m1 + m2;
you can write:
Money total = m1.add(m2);
The logic can be the same. Operator overloading is used when the operator syntax is natural and readable.
Viva Answer
Operator overloading is compile-time polymorphism because the compiler chooses the correct overloaded operator function during compilation based on the operand types.
Quick Check
- Does operator overloading create new operators?
- Why is
m1 + m2resolved at compile time? - When is a named function better than an overloaded operator?