If you overload - like operator-(), it is to be used to the left of the object, however overloading () like operator()() it is used to the right of the object. How do we know which operator is to be used on the left and which ones to be used on the right?
Look at the operator precedence chart. This will tell you the direction the operator associates (binds). Note that some operators have multiple forms with different meanings, such as binary and unary -
. In such cases, you may have multiple overloads, e.g.:
T operator-()
and:
T operator-(const T &o)
The compiler chooses the right one based on the syntactical interpretation of the operator.
See also this useful set of guidelines.
Most unary operators can only be placed at a specified side of their operand. For the two special cases, ++
and --
, see this FAQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With