7

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?

asked Mar 21, 2010 at 4:48
1
  • 2
    This has a simple answer, but from the perspective of someone new to programming I can imagine this could be a source of much headache. +1 Commented Mar 21, 2010 at 4:50

2 Answers 2

3

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.

answered Mar 21, 2010 at 4:50
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Thanks for catching that, Jonathan. Fixed now.
1

Most unary operators can only be placed at a specified side of their operand. For the two special cases, ++ and --, see this FAQ.

answered Mar 21, 2010 at 4:50

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.