According to replies to this thread, operator=
cannot be overloaded as a non-member function. So, for example, the following makes the compiler very angry:
class MyClass
{
// ...
};
MyClass& operator=(MyClass& Left, MyClass& Right)
{
// ...
}
Why is this? I have a container class with getters and setters, so a member function is unnecessary and it would break encapsulation. One of the answers to the aforementioned thread said that it's to make sure the "L-value is received as its first operand," but I don't fully understand what that means. Could someone please clarify?
Additionally, are operator=
, operator()
, operator[]
and operator->
"oddball" cases...? Or should I implement all overloaded operators as member functions...? (I know it's perfectly legal to do otherwise, but I'm looking for the better practice.)
If your class doesn't have an assignment operator (as a member), the compiler generates one by default, just like it generates a copy constructor if you don't provide one.
Therefore it will be "angry" if you try to define a non-member assignment operator later. There will then be two!