My quesitions is about the class data-members initializations. I would like to know the Initialization rules, such as the build-in type (int, double ,float) and user-defined type. If we didn't initialize them, the content of them is undefined or the default constructor will be used?
2 Answers
Initializing bases and members
Initialization of non-static data members is described in C++11 standard 12.6.2 Initializing bases and members:
... if a given non-static data member or base class is not designated by a mem-initializer-id ..., then
- if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in 8.5;
- otherwise, if the entity is a variant member (9.5), no initialization is performed;
- otherwise, the entity is default-initialized (8.5).
After the call to a constructor for class X has completed, if a member of X is neither initialized nor given a value during execution of the compound-statement of the body of the constructor, the member has indeterminate value.
Note: If an object is default initialized and the object is not a class nor array type, no initialization is performed (see 8.5.6).
Example:
struct A {
A();
};
struct B {
B(int);
};
struct C {
C() { } // initializes members as follows:
A a; // OK: calls A::A()
const B b; // error: B has no default constructor
int i; // OK: i has indeterminate value
int j = 5; // OK: j has the value 5
};
Objects with static storage duration
Variables with static storage duration are zero initialized (3.6.2 Initialization of non-local variables):
Non-local variables with static storage duration are initialized as a consequence of program initiation. ...
Variables with static storage duration (3.7.1) ... shall be zero-initialized (8.5) before any other initialization takes place.
User defined types
For user defined types a default constructor is called (if not called explicitly another constructor, see example above). If the constructor is implicitly declared (generated by compiler) the members are initialized according to Initializing bases and members (see above). If the constructor is user defined it's user's responsibility to initialize class members.