r/learncpp • • Aug 16 '18

Why does this print different names?

My understanding is that the default copy constructor copies fields. So when I initialize Person aaron with the fields from *p, I thought *p.name and aaron.name would be pointing to same data since name is actually a pointer. What is going with the pointers and memory?

#include <iostream>

using namespace std;

class Person {

public:

`char* name;`

`int age;`

`/*Person(Person& p) {`

	`name =` `p.name``;`

	`age = p.age;`

`}*/`

};

int main() {

`Person* p;`

`(*p).name = "aaron";`

`(*p).age = 26;`

`Person aaron = *p;`

`aaron.name` `= "aar0n";`

`cout << (*p).name << '\n'; //prints aaron`

`cout <<` `aaron.name` `<< '\n'; //prints aar0n`

`return 0;`

}

1 Upvotes

13 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Aug 16 '18

a solution to that is using:

char name[6]; 

instead of:

char* name;