Reputation: 2540
Why is the memory address of message.pmessage the same before and after the constructor is called? Shouldn't the memory address of message.pmessage be different if it was allocated with new? I'm confused.
Overloaded Operator function
CMessage operator+(const CMessage& aMess) const
{
cout << "Add operator function called." << endl;
size_t len = strlen(pmessage) + strlen(aMess.pmessage) + 1;
CMessage message;
//
cout << &message.pmessage << endl;
cout << message.pmessage << endl;
message.pmessage = new char[len];
message.test = new char[len];
cout << &message.pmessage << endl;
//
strcpy_s(message.pmessage, len, pmessage);
strcat_s(message.pmessage, len, aMess.pmessage);
return message;
}
Constructor
CMessage(const char* text = "Default message")
{
cout << "Constructor called." << endl;
pmessage = new char[strlen(text) + 1]; // Allocate space for text
strcpy_s(pmessage, strlen(text)+1, text); // Copy text to new memory
}
Upvotes: 0
Views: 152
Reputation: 5694
you are printing the address of a pointer inside one object, of course it is always going to be the same. To print out of the address that pointer is pointing to, you can try this
cout << static_cast<void*>(message.pmessage) << endl;
you need static_cast<void*>
because you want to avoid printing the c string.
Upvotes: 4