When will a fundamental C++ type, such as int
or float
, have an unknown initial value?
How does the type of memory allocation factor in, if at all? What about the declaration? What if it's a member of a class
/struct
/union
? Is C++11 different from C++03 or C++98?
I have my suspicions, but no idea if my knowledge is complete (or correct, for that matter)
Any POD data (including all fundamental types) will have an unknown value when both:
new
)Global/static variables, of all types, are set to zero as part of the startup process before main
is called. Constructors are called for types that have constructors before main
1.
Anything not initialized in the constructor is also unknown.
Edit: to clarify, std::string
is a good example of "constructor not initializing everything" - if you have a local std::string str;
, then str
will have a defined "empty string" content, but the content of the actual buffer, or indeed what the buffer points at may not be set to anything meaningful at all - as the implementation may determine based on the length [or some other way] whether there is a buffer available or not once we start using the string to store stuff].
Edit2: As the comment explains, you can also have "hybrid" cases, where parts of a structure is being initialized, e.g. a struct
that contains some elements of "plain data" and some elements that have constructors. The ones that have constructors will have their constructor called. The plain data will not be initialized.
1 It may well be that the code running constructors is part of, or called from inside the "main" function - but if that is the case, it will be "before any of your code in main is started".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With