When using operator overload, the example use reference as a parameter
This is correct. It wants a reference to a single object, not a (possibly null) pointer to an object or array of objects. Also, it's a const
reference, since the function won't be altering the original.
when comparing if the address is equal, why using & on aMess,
Because &aMess
is the address of aMess
. Pointers with the same address by definition point to the same object.
why doesn't use if(this == aMess)?
That's comparing a pointer (this
) to a reference (aMess
) and won't compile unless CMessage::operator CMessage* ()
exists (hopefully it doesn't). If one wanted to compare the values of the objects, they would write if(*this == aMess)
, which would call bool CMessage::operator ==(const CMessage&)
if it exists, or do a binary comparison of the objects if not.
Is &aMess an address of reference?
It's the address of the object. Applying unary &
to a reference does the same thing as applying it to the referenced object.
The whole point of this exercise is that the CMessage
class has heap-allocated storage in it (pointed to by pmessage
) and it could crash if it didn't check if it was copying to itself, because it would delete its storage before copying it.
This function could alternatively have copied the storage first, then changed pmessage
to point to the copy, then deleted the old version, which would avoid the need to check for copy-to-self, but would also result in an unnecessary copy in that case.