In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions.
For objects, their default constructor is called. For example, for std::string
, the default constructor sets it to an empty string. If the object's class does not have a default constructor, it will be a compile error if you do not explicitly initialize it.
For primitive types (pointers, ints, etc), they are not initialized -- they contain whatever arbitrary junk happened to be at that memory location previously.
For references (e.g. std::string&
), it is illegal not to initialize them, and your compiler will complain and refuse to compile such code. References must always be initialized.
So, in your specific case, if they are not explicitly initialized:
int *ptr; // Contains junk
string name; // Empty string
string *pname; // Contains junk
string &rname; // Compile error
const string &crname; // Compile error
int age; // Contains junk
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…