What is the default values for members of a struct and members of a class in c++, and how do these rules differ (e.g. between classes/structs/primitives/etc) ? Are there circumstances where the rules about the default values differs ?
+2
A:
Yeah, there is one. If you initialize an object with the default constructor and use parentheses then the POD members will be zero initialized:
someClass * p = new someClass();
Hans Passant
2010-04-10 20:22:10
+3
A:
There are no differences between structs and classes in this regard in C++. They all are called just class types.
Members of class types have no default values in general case. In order to for a class member to get a deterministic value it has to be initialized, which can be done by
- Default constructor of the member
- Constructor of the enclosing class
- Explicitly specified initializer for object of the enclosing class (that includes value-initialization and initialization with aggregate initializer).
Additionally, all objects with static storage duration are zero-initialized at the program startup.
Aside form the above cases, class members, once again, have no default values and will initially contain unpredictable garbage values.
AndreyT
2010-04-10 20:42:35
If static storage is zero-initialized would depend on the operating system you're running.
jpyllman
2010-04-11 01:25:04
@jpyllman: No. Static storage is always zero-initialized. It is guaranteed (required) by the language, regardless of any operating systems.
AndreyT
2010-04-11 01:29:38
@AndreyT: OK, I've tried to find such info but not finding it. I've always assumed it is undefined unless you set some value.
jpyllman
2010-04-11 02:40:40