0

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 } 

enter image description here

2
  • 2
    Where is there the constructor called? Commented Nov 28, 2013 at 1:31
  • @VladfromMoscow When I declare the object message inside the overloaded operator function. Commented Nov 28, 2013 at 1:33

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.