You touch one of the sticky corners of C ++.
Initializing POD values ββin objects is sticky and depends on several things.
Even I'm not sure that I can correct all the rules correctly, but I believe that @Steve Jessop once wrote an article on SO (although I can find it now).
But some examples:
This class will always be initialized b == false and value = 0.
class A { A() : b(), value() {} B b; int value; };
Without the default constructor, it is clearly more complex:
Here the compiler will create a default constructor for you. But how the default compiler works depends on the situation. The default constructor created by the compiler can perform two different forms of initialization and which is used depending on the context:
- Zero initialization (all POD members are reset)
- Initialization of the value (all members of the POD remain undefined)
Example:
class B { B b; int value; }; // Variables of static storage duration (notably globals) // Will be zero initialized and thus b == false and value = 0 B global; // Initialized int main() { // Object of automatic storage duration or dynamic storage duration // These will depend on how they are declared. // Value Initialization (POD re-mains undefined) B bo1; // b/value undefined B* bp1 = new B; // b.balue undefined // Zero Initialization B bo2 = B(); // b = false, value = 0 B* bp2 = new B(); // b = false, value = 0 // Note: The most obvious syntax for zero initializing a local object // does not work as it is actually interpreted as a forward // declaration of a function; B bo3(); }
Loki Astari Jan 07 2018-11-11T00: 00Z
source share