Search code examples
c++default-constructor

Does the compiler provides different default constructor for automatic & static objects?


I know that compiler provided default constructor doesn't initialize data members of class & struct. Consider following example:

#include <iostream>
struct Test
{
     int a,b;                      // oops,still uninitialized
};
int main()
{
      Test t;                      // compiler won't initialize a & b
      std::cout<<t.a<<' ' <<t.b;   // a & b has garbage values
}

But as we know if object is static then class members will be always 0 initialized automatically.

#include <iostream>
struct Test
{
     int a,b;              // both a & b will be 0 initialized              
};
int main()
{
      static Test t;               // static object
      std::cout<<t.a<<' ' <<t.b;   // a & b will always be 0 by default
}

So my questions are:

1) Does the compiler provides different default constructor for automatic & static objects?

2) Will the compiler generate different code for the above 2 programs?


Solution

  • Objects with static storage duration are always zero-initialized before any other kind of initialization (cf. [basic.start.init]). Objects with automatic storage duration are not. The constructor has nothing to do with it.