r/learncpp • u/Tyephlosion • 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
View all comments
Show parent comment
2
u/[deleted] Aug 17 '18
Yep, you're right.
Yep, you're right again.
so "aaron" is a value we don't have a name to it's address, it's only a value hard-coded by you, so when you do:
you're saying: "Move this hard-coded value 'aaron' to the address of p->name" . And when you copy p to aaron you also create a COPY of Person::name not a reference, so aaron.name will have the same value but not the same address of p->name, because another variable was allocated in memory. This table can exemplify better: