Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading in C++

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?

like image 787
shreyasva Avatar asked Mar 21 '10 04:03

shreyasva


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.

like image 59
Matthew Flaschen Avatar answered Nov 04 '22 08:11

Matthew Flaschen


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

like image 25
Alex Martelli Avatar answered Nov 04 '22 09:11

Alex Martelli