Binary Arithmetic Operators + - *
The binary arithmetic operators are interesting because they don't modify either operand - they actually return a new value from the two arguments. You might think this is going to be an annoying bit of extra work, but here is the secret:
Define your binary arithmetic operators using your compound assignment operators.
There, I just saved you a bunch of time on your homeworks.
So, you have implemented your += operator, and now you want to implement the + operator. The function signature should be like this:
// Add this instance's value to other, and return a new instance
// with the result.
const MyClass MyClass::operator+(const MyClass &other) const {
MyClass result = *this; // Make a copy of myself. Same as MyClass result(*this);
result += other; // Use += to add other to the copy.
return result; // All done!
}
Simple!
Actually, this explicitly spells out all of the steps, and if you want, you can combine them all into a single statement, like so:
// Add this instance's value to other, and return a new instance
// with the result.
const MyClass MyClass::operator+(const MyClass &other) const {
return MyClass(*this) += other;
}
This creates an unnamed instance of MyClass, which is a copy of *this. Then, the += operator is called on the temporary value, and then returns it.
If that last statement doesn't make sense to you yet, then stick with the other way, which spells out all of the steps. But, if you understand exactly what is going on, then you can use that approach.
You will notice that the + operator returns a const instance, not a const reference. This is so that people can't write strange statements like this:
MyClass a, b, c;
...
(a + b) = c; // Wuh...?
This statement would basically do nothing, but if the + operator returns a non-const value, it will compile! So, we want to return a const instance, so that such madness will not even be allowed to compile.
To summarize, the guidelines for the binary arithmetic operators are:
- Implement the compound assignment operators from scratch, and then define the binary arithmetic operators in terms of the corresponding compound assignment operators.
- Return a const instance, to prevent worthless and confusing assignment operations that shouldn't be allowed.