Logo Questions Linux Laravel Mysql Ubuntu Git Menu

How a class that does not initialize its all members in its constructor to be initialized in C++11




The code is like

class C{
             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 value m2 is to be initilized. I think c is value initialized, and m2 is default initialized.

I test it with C++11 and g++4.8.4, and m2 seems always 0. I think 0 is default initializing, but default initializing is not 0. So initializing to 0 can be guaranteed?

like image 810
Master Qiao Avatar asked Mar 09 '23 06:03

Master Qiao

1 Answers

c is copy initialized, and not value initialized. m2 is in fact default initialized, yes, but that does not mean that its value is always 0 (that would be guaranteed by value and aggregate initialization).

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

struct X {};
X x{}; // aggregate initialized
like image 115
Rakete1111 Avatar answered Apr 29 '23 14:04