Operator Overloading in C++: Giving Operators Custom Behavior
What is Operator Overloading in C++: Giving Operators Custom Behavior? Operator overloading enables custom classes to respond intuitively to standard C++ operators using operator functions (e.g. operator+, operator==). Operators ca...
How do you overload operators (+, -, ==, <<) in C++, and what operators cannot be overloaded?
Explanation & In-Depth Details
- Member Overload: Left-hand operand must be an instance of the class (`obj1 + obj2`).
- Non-Member (Friend) Overload: Symmetric conversions allowed for both left and right operands (`2.0 * vector` and `vector * 2.0`).
```text
OPERATORS THAT CANNOT BE OVERLOADED:
┌─────────────────────────────────────────────────────────────┐
│ • Scope Resolution: :: │
│ • Member Selection: . │
│ • Pointer-to-Member: .* │
│ • Ternary Conditional: ?: │
│ • Size Query: sizeof │
│ • Type Identification: typeid │
└─────────────────────────────────────────────────────────────┘
```
Code Example
#include <iostream>
class Vector2D {
public:
double x, y;
Vector2D(double xVal = 0.0, double yVal = 0.0) : x(xVal), y(yVal) {}
// Overload Binary + (as member function)
Vector2D operator+(const Vector2D& other) const {
return Vector2D(x + other.x, y + other.y);
}
// Overload Equality ==
bool operator==(const Vector2D& other) const {
return (x == other.x) && (y == other.y);
}
// Overload Stream << (as non-member friend function)
friend std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
os << "Vector2D(" << v.x << ", " << v.y << ")";
return os;
}
};
int main() {
Vector2D v1(3.0, 4.0);
Vector2D v2(1.5, 2.5);
Vector2D sum = v1 + v2; // Calls operator+
std::cout << "v1: " << v1 << "\n";
std::cout << "v2: " << v2 << "\n";
std::cout << "Sum: " << sum << "\n";
std::cout << "Are equal: " << (v1 == v2 ? "YES" : "NO") << "\n";
return 0;
}Interview Question & Tips
A: No. Operator overloading preserves the existing C++ syntax, precedence, associativity, and arity (number of operands) of built-in operators.
Q: What is the spaceship operator `<=>` introduced in C++20?
A: The three-way comparison operator `<=>` generates all six relational comparison operators (`<`, `<=`, `>`, `>=`, `==`, `!=`) automatically when defaulted (`auto operator<=>(const MyClass&) const = default;`).
Best Practices
• Implement binary arithmetic operators (`+`) in terms of compound assignment operators (`+=`).
• Use C++20 three-way comparison `<=>` to simplify relational operator implementations.
This study reference for Operator Overloading in C++: Giving Operators Custom Behavior is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: