MyClass & operator=(const MyClass &rhs);
What is the meaning of "&"? Why not is My Class
instead of MyClass &
?
MyClass & operator=(const MyClass &rhs);
What is the meaning of "&"? Why not is My Class
instead of MyClass &
?
The &
simply means that the return value of operator =
is a reference.
This has nothing to do with operator overloading. It's the same syntax with a normal function definition:
MyClass& foo()
{
return *this; // returns a reference to MyClass instance
}
MyClass foo()
{
return *this; // returns a copy of MyClass instance
}
returning MyClass&
is just to make operator '=' work in chain.
Returning MyClass&
or something different doesn't add any effect in overloading '='.
Returing MyClass&
helps us use '=' similar the way we use it on built-in data types.
eg.
int x = y = z = 123;
For similar discussion, refer Thinking in C++, (Discussion on iostreams).