Alex Rivera | Logout

Default and value initialization of POD types in C++

Asked 2013-03-04T22:21:28.600
24

I know some POD variables are initialized by default to a meaningful value but others are not. (POD types include int, float, pointers, unions, arrays of POD types, structs of POD types, etc.)

How does scope and storage class affect initialization of POD types?

Specifically, which of the following will be initialized implicitly to a known value (e.g., 0 for integer types) (i.e., value initialization) and which are defined with an indeterminate value (i.e., default initialization):

  • Local variables with automatic storage
  • Static local variables
  • Static global variables
  • External variables
  • Variables allocated with new
  • POD members of a class (without explicit initialization in a constructor)

I know there are existing questions relating to some of these situations, but none comprehensive (they only address specific situations).

Edit
Report

1 Answer

13

If we're only talking about PODs then only local and global statics and external variables because they have to be defined somewhere.

PODs allocated with new are also initialized sometimes - if you make the initialization explicit:

int* x = new int();

will create an int initialized to 0 with x pointing to it, whereas

int* x = new int;

will have x point to an uninitialized int.

Sometimes - POD class members - they can be initialized explicitly (without being in a constructor):

struct X
{
   int x;
};

X x;        //x.x is not initialized
X y = X();  //y.x is 0
answered 2013-03-04T22:27:31.540

Your Answer