1
iarray<T>& operator = (iarray<T>& v) 

Why the return type is iarray<T>& not iarray<T> ?

UPDATE

Can someone elaborate in great detail why iarray<T> const &v ?

3
  • 1
    Note that it should normally be iarray<T> &operator=(iarray<T> const &v); Commented Oct 17, 2010 at 3:35
  • Can you elaborate why iarray<T> const &v? Commented Oct 17, 2010 at 4:04
  • @Alan: so the value of a temporary (which can't be bound to a non-const ref) can be assigned. Commented Oct 17, 2010 at 5:19

3 Answers 3

8

Because you don't want to return a copy of the array just for the sake of chaining. Returning a reference is a better option as it doesn't result in a copy being constructed.

Sign up to request clarification or add additional context in comments.

Comments

3

Because then you can chain them efficiently, eg.

a = b = c; 

See the C++ FAQ.

Comments

0

Why the return type is iarray& not iarray ?

Because the result of an assignment is a reference to what just got assigned. For example, the result of a = b should be a reference to a so you can chain them together like in c = a = b; which is effectively a = b; c = a;. (Yes, people like doing this on rare occasions; no, I don't know why it's such a hardship to break it into two lines.) Thus your code should look like:

iarray<T>& iarray<T>::operator = (const iarray<T>& v) { // ... copy `v`'s state over this object's ... return *this; } 

Can someone elaborate in great detail why iarray const &v ?

Because an assignment operation has no business changing the right-hand side; it is unexpected behavior. If you have some funky thing in your object that needs to change, like a reference count, then you should prefer declaring that one part mutable over disallowing const right-hand side expressions. You can pass a non-const value in for a const parameter, but the reverse is not true.

2 Comments

I think chaining also works if the return type is iarray<T>,dont you?
It results in the creation and destruction of an unnecessary temporary object. So return a reference. Make it a const reference if it makes you feel better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.