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 16 '18
When you use char n[] and then writes: p->name = n, you are saying "p->name pointer points to address of n", but when you write: p->name = "aaron", "aaron" don have a place (a address), "aaron" is moved to p->name, because "aaron" is a value, and n has a value.