3

Is there any difference regarding the initialization of the x member variable in these cases:

struct A {
    int x;
    A() {}
};

struct B {
    int x;
    B() : x(0) {}
};

struct C {
    int x;
    C() : x() {}
};

For all these cases, in the tests I did, x is always set to the initial value of 0. Is this a guaranteed behavior? Is there any difference in these approaches?

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • 2
    `A::x` is uninitialized. [Demo](http://coliru.stacked-crooked.com/a/7e1e9885623dc23b). – Jarod42 May 25 '21 at 13:52
  • *in the tests I did, x is always set to the initial value of 0* -- You can't do tests like this and conclude this is how C++ works. The value of `0` is just as uninitialized as any other value. You know a value is initialized by following the rules of initialization, which `B` and `C` do successfully. – PaulMcKenzie May 25 '21 at 13:56
  • `struct A { int x = 0; /*...*/ }` might be interesting to compare... – Aconcagua May 25 '21 at 13:58
  • 1
    *"You can't do tests like this and conclude"* @PaulMcKenzie: That's why OP ask question ;-) That kind of test is a first step, which might reject some hypothesis though. – Jarod42 May 25 '21 at 13:59
  • 1
    Note: Simple tests for behaviour like this can easily be misleading. Do not use zero. It is too often a default filler value. For example, a program starting and clearing all of its initial memory to 0 is not uncommon. If you don't give the program a work out before running the test you'll likely get exactly the number, 0, you expected. – user4581301 May 25 '21 at 14:00

1 Answers1

4

For B::B(), x is direct-initialized as 0 explicitly in member initializer list.

For C::C(), x is value-initialized, as the result zero-initialized as 0 in member initializer list.

On the other hand, A::A() does nothing. Then for objects of type A with automatic and dynamic storage duration, x will be default-initialized to indeterminate value, i.e. not guaranteed to be 0. (Note that static and thread-local objects get zero-initialized.)

songyuanyao
  • 169,198
  • 16
  • 310
  • 405