Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member variables initialization [duplicate]

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?

like image 971
Pietro Avatar asked Jan 23 '26 19:01

Pietro


1 Answers

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

like image 63
songyuanyao Avatar answered Jan 25 '26 09:01

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!