0

The following code is quite stupid and has no purpose at all (I tried to play with move (&&) but that turned out. Right now, this code has nothing to do with move, and my question is not related to move).

class X
{
public:
    X(int num) : m_a(num) { std::cout << "ctor" << std::endl; }
    X(const X& other) : m_a(other.m_a) {std::cout << "CCTOR" << std::endl; }

    int m_a;
};


int main()
{
    int i = 11;
    X x1(X(i));

    std::cout << &i << " " << x1.m_a << std::endl;
    std::cout << typeid(x1).name() << std::endl;

return(0);
}

commenting out the first print, the output is:

F1XS_E

F represents a function. Not commenting out the first print results in a linking error:

request for member ‘m_a’ in ‘x1’, which is of non-class type ‘X(X)’

What this code is expected to do is: Create a temporary X, using the i as parameter, and calling the copy constructor for x1. I am well aware that the compiler can optimize it, and my expectations are not interesting lol Anyway, that is not my problem. For reasons I can't really explain (and that's my question), the compiler refers to this line:

X x1(X(i));

as a function declaration:

X x1(X i); // function x1, receives X by value (parameter name: i) and returns X by value

Why is that? if I changed the i to a literal integer (X x1(X(11));) - it wouldn't complain. But why does the compiler think the i is a function parameter, and not a variable? I KNOW it is stupid, and I can simply write X x1(i), I just can't really understand why it'd complain when I write it the way I did. Or could it be the reason? This is a stupid way of writing so even the compiler thinks we can't be that stupid?

It works just fine using { } (X x1 {X(i)};)

Side note: I just found out function parameters can be written in parentheses that will be ignored. So void foo(int (((num)))); IS a valid function declaration that receives the parameters num, which in an int.

Thanks.

Sakebi
  • 13
  • 3

0 Answers0