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
+
should perform addition or concatenation==
should test for equality+=
should modify the left operand by adding the right operandIf 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:
Instead of overloading operators to do unexpected things, create appropriately named functions for those operations. This makes your code's behavior clear and predictable.
Answers to questions are automatically generated and may not have been reviewed.
This lesson introduces operator overloading, a fundamental concept to create more intuitive and readable code by customizing operators for user-defined types
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course