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?
2 Answers
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.
2 Comments
Jonathan Leffler
Does 'operator-()' really return nothing - shouldn't it return a value of the appropriate type that is either the negation of the value or the difference between the values?
Matthew Flaschen
Thanks for catching that, Jonathan. Fixed now.
Most unary operators can only be placed at a specified side of their operand. For the two special cases, ++ and --, see this FAQ.
1 Comment
Donald Duck is with Ukraine
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.