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?

5
  • 2
    A::x is uninitialized. Demo. Commented May 25, 2021 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. Commented May 25, 2021 at 13:56
  • struct A { int x = 0; /*...*/ } might be interesting to compare... Commented May 25, 2021 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. Commented May 25, 2021 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. Commented May 25, 2021 at 14:00

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.