7

This code was published in http://accu.org/index.php/cvujournal, Issue July 2013. I couldn't comprehend the output, 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()
{
    l l(42);
    l.load();
    std::cout << x << std::endl;
}

Output:

--C1
0

I was expecting:

--C2
42

Any Explanation ?

Zoltán Schmidt
  • 1,286
  • 2
  • 28
  • 48
Maverick
  • 366
  • 1
  • 5
  • 11

1 Answers1

20

i(x); is equivalent to i x;, with a redundant pair of parentheses thrown in. It declares a variable named x of type i, default-initialized; it does not create a temporary instance of i with x as the constructor's parameter. See also: most vexing parse

aschepler
  • 70,891
  • 9
  • 107
  • 161
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85