motto3 contains:
The devil takes care of his own. If you sup with the devil use a long spoon.
The devil takes care of his own. If you sup with the devil use a long spoon.
Destructor called.
Destructor called.
Destructor called.
Press any key to continue . . .
You've not implemented all the necessary default methods, plus you have a memory leak as I've indicated below.
1 2 3 4 5 6 7 8 9 10 11
// Overloaded addition operator
CMessage operator+(const CMessage& aMess) const
{
cout << "Add operator function called." << endl;
size_t len{ strlen(m_pMessage) + strlen(aMess.m_pMessage) + 1 };
CMessage message; // this allocates m_pMessage and copies in "Default message"
message.m_pMessage = newchar[len]; // you're overwriting the pointer, loosing the original message
strcpy_s(message.m_pMessage, len, m_pMessage);
strcat_s(message.m_pMessage, len, aMess.m_pMessage);
return message; // You don't have a copy or move, but you do have a destructor that releases memory--could get messy
}
I stepped through the program, and the CMessage message; does not allocate m_pMessage and does not copy in the "Default message". message is essentially an uninitialized object. I suspect it may be because it is a rhs object instead of a lhs object.
FurryGuy,
Why wasn't line 83 overwritten by line 87? Are there two copies of motto3?
I stepped through the program, and the CMessage message; does not allocate m_pMessage and does not copy in the "Default message". message is essentially an uninitialized object.
CMessage motto3;
This calls the default constructor, which in your case is:
1 2 3 4 5 6 7
CMessage(constchar* text = "Default message")
{
cout << "Constructor called." << endl;
size_t length{ strlen(text) + 1 };
m_pMessage = newchar[length]; // Allocate space for text
strcpy_s(m_pMessage, length, text); // Copy text to new memory
}
Why does motto3 print twice (line 91)? See output.
It doesn't. motto3="The devil takes care of his own. If you sup with the devil use a long spoon.\nThe devil takes care of his own. If you sup with the devil use a long spoon.\n"