Search code examples
c++constructorinitialization

Member variables initialization


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?


Solution

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