Alan Ning:
I have a question on assignment operator.
People in my company likes to make their assignment operator const.
So we have
const A& operator=(const A& obSrc)
But everywhere online, I see
A& operator=(const A& obSrc)
What is the difference? They both seem to work just fine.
The whole point of operator overloading is that you can get your own class
objects to behave like intrinsic types, e.g. add to them, dereference them,
array subscript them.
C++, however, gives you full control -- almost _too_ full control -- over
how you wish to implement an operator for your given class. For instance, I
can make the multiplication operator perform a division instead of a
multiplication:
MyClass &MyClass:
perator*=(MyClass const &rhs)
{
some_member /= rhs.some_member;
return *this;
}
This is perfect OK... but is it good? Of course, you'd have no know the
requirements of the project and so forth to give a definitive answer, but
the general answer is: No, this is not good, it's operator abuse.
Let's look at the assignment operator. With normal types, you can do the
following:
int a,b,c,d,e,f,g=5;
a=b=c=d=e=f=g;
If you try this with your sample code which returns a "MyClass const&"
rather than a "MyClass&", then you'll get a compile error.
In my own opinion, the general view of this should be that it's operator
abuse -- i.e. it's not natural to not be able to perform multiple
assignments in the one statement.
Of course, there are umpteen bad programming styles out there which seem to
flourish, so if you like the bastardisation of returning a "MyClass
const&", then go for it.
My own opinion however is that it's operator abuse.
(But then again, one size doesn't fit all -- you may be writing a strange
class where you wouldn't want to allow multiple assignments, but of course,
this is the "odd-one-out" scenario).