Unconventional Operator Behavior
Can I overload operators to do completely different things than what they normally do? Like making +
do multiplication?
While C++ technically allows you to make operators behave however you want, doing so is generally considered poor practice. Let's look at why, and what guidelines you should follow:
#include <iostream>
struct BadVector3 {
float x, y, z;
// BAD: + operator performs multiplication
BadVector3 operator+(
const BadVector3& other) const {
// Multiplying instead of adding!
return BadVector3{
x * other.x,
y * other.y,
z * other.z
};
}
};
struct GoodVector3 {
float x, y, z;
// GOOD: + operator performs addition as expected
GoodVector3 operator+(
const GoodVector3& other) const {
return GoodVector3{
x + other.x,
y + other.y,
z + other.z
};
}
};
int main() {
BadVector3 v1{2, 3, 4};
BadVector3 v2{3, 4, 5};
// Misleading! Actually multiplies
BadVector3 result{v1 + v2};
std::cout << "Unexpected result: "
<< result.x << "\n"; // Prints 6, not 5!
}
Unexpected result: 6
Guidelines for Operator Behavior
- Follow the principle of least surprise - operators should behave as users expect
+
should perform addition or concatenation- should perform multiplication or scaling
==
should test for equality- should perform subtraction or negation
+=
should modify the left operand by adding the right operand
Why These Guidelines Matter
If operators behave unexpectedly:
Vector3 pos{1, 2, 3};
Vector3 movement{4, 5, 6};
// Developer expects addition,
// but gets multiplication instead!
Vector3 newPos{pos + movement};
Breaking these conventions makes code:
- Harder to read and understand
- More prone to bugs
- Less maintainable
- Confusing for other developers
Instead of overloading operators to do unexpected things, create appropriately named functions for those operations. This makes your code's behavior clear and predictable.
Operator Overloading
This lesson introduces operator overloading, a fundamental concept to create more intuitive and readable code by customizing operators for user-defined types