I'd like to know why assignment operator doesn't return a const reference?

 
classtype& operator=(const classtype&);


I think returning a const may avoid (obj1 = obj2) = obj3.
Your example (obj1 = obj2) = obj3; could be written as:
1
2
obj1 = obj2;
obj1 = obj3;

The first assignment seems a bit pointless, unless the assignment has a side-effect.

Nevertheless, we do know that the left side of assignment cannot be const. Therefore, the returned reference could be either const or non-const. While there are less obvious need for the non-const, it would be an unnecessary restriction to enforce const.
thanks for reply, kes.
After reading your words, I think I still has no concrete reason to persuade myself(It may be my poor English to understand your words?), But I think for now, sticking to it is a good choice.
For the built-in types like int, the assignment operator returns a reference to the left side. This goes back to C compatibility I think.

You can define your operator= to do whatever you want. Returning a const reference will prevent people from doing things like your example, but will also prevent
(obj1 = obj2).func()
if func() is not const. Why would you want to prevent this? Let the client code make that call.
Topic archived. No new replies allowed.