Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default initialization in C++

Tags:

I was asking myself something this morning, and I can't find the words to properly "google" for it:

Lets say I have:

struct Foo {   int bar; };  struct Foo2 {    int bar;    Foo2() {} };  struct Foo3 {    int bar;    Foo3() : bar(0) {} }; 

Now if I default instantiate Foo, Foo2 and Foo3:

Foo foo; Foo2 foo2; Foo3 foo3; 

In which case(s) is the bar member properly initialized ?

(Well Foo3 obviously explicitely initialize it and is only showed here to explicit the difference with Foo2 so the question is mainly about the first two.)

Thank you ! :)

like image 798
ereOn Avatar asked Jun 06 '11 12:06

ereOn


People also ask

Is an int initialized to 0 in C?

Please note that the global arrays will be initialized with their default values when no initializer is specified. For instance, the integer arrays are initialized by 0 . Double and float values will be initialized with 0.0 . For char arrays, the default value is '\0' .

What is initialization list in C?

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.

What is the default value of an int in C?

The default value of Integer is 0.

Does C automatically initialize variables?

Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location!


2 Answers

Only foo3 will be in all contexts. foo2 and foo will be if they are of static duration. Note that objects of type Foo may be zero initialized in other contexts:

Foo* foo = new Foo(); // will initialize bar to 0 Foo* foox = new Foo; // will not initialize bar to 0 

while Foo2 will not:

Foo2* foo = new Foo2(); // will not initialize bar to 0 Foo2* foox = new Foo2; // will not initialize bar to 0 

that area is tricky, the wording as changed between C++98 and C++03 and, IIRC, again with C++0X, so I'd not depend on it.

With

struct Foo4 {    int bar;    Foo4() : bar() {} }; 

bar will always be initialized as well.

like image 133
AProgrammer Avatar answered Oct 14 '22 03:10

AProgrammer


Since bar is a built-in type its default initialization will be undefined for Foo1 and Foo2. If it would have been a custom type, then the default constructor would have been called, but here it's not the case.

Lesson: always initialize your variables.

like image 26
Jesse Emond Avatar answered Oct 14 '22 03:10

Jesse Emond