I was trying to understand how objects create and initialize constructors. I want to create an object with a "person class" with "*name" feature and test if the name pointer is NULL or not once I create a object.
I first test with dynamic allocation "new" to create the object and the pointer is null. However, If I use static to create the object and the pointer is not null.
class person{
public:
string *name;
person(){
}
~person(){}
};
The above is class definition.
int main(){
person *jack = new person();
cout << jack->name << endl;
if(jack->name == NULL){
cout << "is null" << endl;
} else{
cout << "not null" << endl;
}
return 0;
}
The above will output: 0x0 , is null
int main(){
person louis = person();
cout << louis.name << endl;
if(louis.name == NULL){
cout << "is null" << endl;
} else{
cout << "not null" << endl;
}
return 0;
}
The above will output: 0x7ffeee80b918, not null
Moreover, if I put the two together:
int main(){
person *jack = new person();
cout << jack->name << endl;
if(jack->name == NULL){
cout << "is null" << endl;
} else{
cout << "not null" << endl;
}
person louis = person();
cout << louis.name << endl;
if(louis.name == NULL){
cout << "is null" << endl;
} else{
cout << "not null" << endl;
}
return 0;
}
The above will output: 0x0, is null, 0x0, is null.
I was trying to figure out why using "new" or not will have a different result on the "name" pointer?
With "new" the name pointer will be NULL Without "new" the name pointer will not be NULL
Moreover, If I put create two objects, the first one creates with new and the second one creates without new. the result will all become NULL. why the first object will affect the name pointer on the second object?