2
votes

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?

2

2 Answers

3
votes

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.

-1
votes

As I studied, Class provide a default constructor (in any case). So it doesn't matter that your are creating a static object or normal object. There is only a difference is that value of local variable has been initialized by zero.