When I use an initialization list:
struct Struct {
Struct() : memberVariable() {}
int memberVariable;
};
the primitive type (int
, bool
, float
, enum
, pointer) member variable is default-initialied. Is the value it gets implementation defined or is it the same for all implementations?
0
If you call
()
on a primitive, the effect is the same as assigning the default value it would have been given if it had been static.For primitive types, default initialisation means that the object is initialised with 0, 0.0 or NULL as appropriate for the type.
Edit: The above is valid for C++98. In C++03, the terms got redefined a bit. Now, using an initialiser of
()
(which is syntactically only possible for member-objects) results in value initialisation, which for primitive types means that the appropriate value of 0, 0.0 or NULL gets stored.You are not correct. The object is not default-initialized but value-initialized. And its value is well-defined
Note that zero is in the range of values for any enumeration, even if it doesn't contain an explicit enumerator with that vaue, so it's safe to initialize an enumeration variable to that value.
In particular for pointer to data members, the representation used in practice is not all-zero bits. In the so-called C++ Itanium ABI used by at least GCC and Clang, pointer to data members have an all-one bits null representation.
Native types like int usually get a
garbage value
, eg. whatever happens to reside in the memory area it is created in. However this is not defined in the standard, and it might also be initialized to 0, which is quite common in eg. debug builds.EDIT. But basically, you should never trust an uninitialized variable to hold something specific; Always define the values yourself.
The Standard says (
8.5/5
).
.
So the value would be same for all implementations.
Struct
is a non-POD type soEDIT :
As @Johannes noticed the primitive type (int, bool, float, enum, pointer) member variable is
value-initialized
notdefault initialized
.It depends on how you instantiate a class, if you use ClassName() the POD classes are default initialized to zero for non POD class default constructor is called but if you use ClassName, without the parentheses no default initialization takes place.