I am trying to understand why references are used when overloading a C++ operator. For example, in the following piece of code:
GenericObject& operator=(const GenericObject &rhs)
{
if (&rhs == this)
return *this;
objectAttribute = GenericObject.objectAttribute;
return *this;
}
I have three questions:
- Why does the function return a reference?
- Why does the function take in a reference? Is it to avoid the expense of copying the contents of the object (which would be necessary if a GenericObject object was the parameter instead of a reference to a GenericObject)?
- Why is a reference used in the third line when comparing the right hand side to this?