Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the output of the following code? [duplicate]

Tags:

c++

struct

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 ?

like image 663
Maverick Avatar asked Jul 17 '13 19:07

Maverick


1 Answers

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

like image 169
Igor Tandetnik Avatar answered Sep 27 '22 17:09

Igor Tandetnik