Why return object& when overloading operator=?

Hi all,

Why do most c++ tutorials on overloading operator= suggest that the operator= return object& ? In code form:

Why
1
2
3
4
5
class object
{
public:
  object& operator=(object& o);
};

instead of
1
2
3
4
5
class object
{
public:
  void operator=(object& o);
};

?

Thanks for explaining! (perhaps it is something important I should know?)
It's traditional behavior that the assignment operator returns the modified value of the left-hand operator.
For example, ((a=8)==8) is true.
Someone using your code might make that assumption, so if you change this, you better make a very clear note on the documentation.
Last edited on
1
2
object a, b, c( /* initial value(s) */ );
a = b = c;  // only makes sense if operator = returns an object &. 

Thanks to both, all understood!

I wouldn't want anyone who uses expressions such as a=b=c; to use my code lol... not that anyone would ever use it ... :)
Last edited on
Topic archived. No new replies allowed.