As a class that does not initialize all its members in its constructor for initialization in C ++ 11

The code is similar to

class C{
       public:
             int m1;
             int m2;
             C(int m);
}
C::C(int m):m1(m){};
int main(){
       C* c = new C(1);
       cout << c->m2 << endl;
}

I want to know what m2 value should be initialized. I think c is initialized with a value, and m2 is initialized by default.

I am testing it with C ++ 11 and g ++ 4.8.4, and m2 is always 0. I think 0 is initialized by default, but the initialization is not 0. By default, can you guarantee initialization to 0?

+4
source share
1 answer

c , . m2 , , , 0 ( ).

int(); // value initialized - always 0
int{}; // value initialized - always 0
int a; // default initialized - indeterminate value

struct X {};
X x{}; // aggregate initialized
+7

Source: https://habr.com/ru/post/1684178/


All Articles