//Overloaded assignment operator for CMessage objects
CMessage& operator=(const CMessage& aMess)
{
//Release memory of 1st operand
delete[] pmessage;
pmessage = newchar[ strlen(aMess.pmessage) + 1];
//Copy 2nd operand string to 1st
strcpy(this->pmessage, aMess.pmessage);
//Return a reference to 1st operand
return *this
}
I would like to know why you return a reference from the assignment operator function. The function does complete the assignment operation, and the object on the right of assignment will be copied to the left. It has something to do with foo.operator=(baz.operator=(bar)) so I think you have to at least return a CMessage object.
If the return type is just CMessage, it will not be legal because a temporary copy of the original object is actually returned, and the compiler will not allow a member function call using a temporary object. CMessage is not an lvalue. So I think the only way to get this to compile is return it as a reference.
I've provided compilable code.
And if you see the temporary object was created by copy contructor which was called by operator=.
If you returns by reference copy contructor will not be called.
And there is no problem with life time in both cases.
I need an if statement for when I make a mistake and have something like foo = *fooPtr.
Thanks for your time, I guess the question was really, "Does it need to return anything?"
Superficially the object on the right will be copied to the object on the left. I guess it depends on how it is used.
I see the difference now that I looked at the outputs.