Alan
Alan

Reputation: 5189

operator overloading

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 ?

Upvotes: 1

Views: 157

Answers (3)

Charlie Martin
Charlie Martin

Reputation: 112346

Because then you can chain them efficiently, eg.

a = b = c;

See the C++ FAQ.

Upvotes: 3

Mike DeSimone
Mike DeSimone

Reputation: 42795

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.

Upvotes: 0

OJ.
OJ.

Reputation: 29401

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.

Upvotes: 8

Related Questions