this is an assignment operator. &rhs != this is confusing. my questions: rhs is a reference of Message type. What does &rhs mean? what does & do (a memory address of a reference?)?
Another question is about return *this . since we want a reference to type Message, but *this is a Message typed object, right? How can we return an object to a reference?
Message& Message::operator=(const Message &rhs)
{
if (&rhs != this)
{
some functions;
}
return *this;
}
&rhsmeans address of the object which reference is referecing to.This is will print
true.A reference is not a different object; it is just a syntactic sugar of pointer, which points to the same object whose reference it is. So when you write
return this, it returns a pointer to the object, but if you writereturn *this, it returns either a copy of the object, or reference to the object, depending on the return type. If the return type isMessage &, then you tell the compiler that “don’t make a copy and instead return the same object“. Now the same object is nothing but a reference. A reference of an object can be made anytime. For example, see the declaration ofrhsabove; it isconst Message & rhs = a, since the targer type is mentioned as reference type, you’re making a referencerhsof the objecta. It is that simple.