So I am trying real hard to understand the rules of initialization in C++.
I wrote the following code:
struct B { int i; // this prevents the definition of an implicit default constructor B( int j ) : i(j) {} }; struct C { int i; // i is not mentioned in the initializer list // the compiler will call default constructor for i C() {} }; int main() { int x( 1 ); cout << " x = " << x << endl; // error: no matching function for call to ‘B::B()’ //B b4 = B(); //cout << " b4.i = " << b4.i << endl; C c1; cout << " c1.i = " << c1.i << endl; } 1) x is correctly initialized to 1, but I don't understand the notation "int x(1)". It's not value-initialized (we would write "int x = int()", and then x would be 0). It's not a constructor call either, because built-in types do not have constructors. Besides, the following page clearly says that: "Only objects of classes with constructors can be initialized with the function-style syntax".
http://msdn.microsoft.com/en-us/library/w7wd1177(v=vs.100).aspx
2) It won't compile if I uncomment the creation of b4. Because I defined a constructor, the compiler doesn't generate an implicit default constructor. This is fine. But why does this prevent the creation of a temporary value-initialized object using "B()"? Writing "B()" is never a constructor call, is it?
3) As explained in the comments of class C, i is not mentioned in the initializer list. Therefore, it should be default-initialized, which means undefined for int type. But the output is "c1.i = 0" every time I run the program.
Thanks.
int i{};. And there's a very quick answer to #3: Reading the value is undefined behaviour.