operator

Apr 2, 2012 at 3:21pm
What is the difference between

return_type operator SYMBOL (argument)

and

return_type &operator SYMBOL (argument)

and what makes (&) necessary for the assignment related overloading?
Last edited on Apr 2, 2012 at 3:24pm
Apr 2, 2012 at 3:29pm
and how should I look at it?

1. return_type (&operator) SYMBOL (argument)

or

2. (return_type&) operator SYMBOL (argument)
Apr 2, 2012 at 3:33pm
As for the first one I have no clue, and will take it is another syntax of C++, whereas the second one (as far as I think) will hand over the reference of the return.
Last edited on Apr 2, 2012 at 6:38pm
Apr 2, 2012 at 5:14pm
Frankly speaking, there only difference is that in first case you will return a copy of an object, and in the second case - reference to it. It's not an requirement, but it's common practice to return reference to the rhs object from assignment or compound operators.

As for your second question, 2 is the correct way to look at it.

Also, consider something like this:

x = y = z;

If you won't return a reference from operator=, you'll have a big overhead on calling copy constructors and temporary object creation. Most common implementation for the "reference" version is to add

But you can virtaully return almost anything from your operator.
Last edited on Apr 2, 2012 at 5:15pm
Topic archived. No new replies allowed.