What does the following code output?

This code was published at http://accu.org/index.php/cvujournal , July 2013 issue. I could not understand the result, any explanation would be helphful

#include <iostream> int x; struct i { i() { x = 0; std::cout << "--C1\n"; } i(int i) { x = i; std::cout << "--C2\n"; } }; class l { public: l(int i) : x(i) {} void load() { i(x); } private: int x; }; int main() { ll(42); l.load(); std::cout << x << std::endl; } 

Output:

 --C1 0 

I expected:

 --C2 42 

Any explanation?

+7
c ++ struct
source share
1 answer

i(x); equivalent to ix; with an extra pair of brackets. It declares a variable named x type i , by default it is initialized; it does not create a temporary instance of i with x as a constructor parameter. See Also: Most Unpleasant Parsing

+20
source share

All Articles