Search code examples
c++functionobjectmost-vexing-parse

C++ Why is variable a function and not an object?


This title may not be completely accurate--it's based on my best guess on what is happening and I figured it was better than "Can someone explain what is happening with this code?"

Anyway, I have this code:

class Class1 { };

class Class2
{
public:
   Class2(Class1 other){}
};

void func(Class2 x){}

int main()
{
   Class2 x(Class1());
   func(x);             //Compile Error

   Class1 y1;
   Class2 y2(y1);
   func(y2);            //Compiles fine
   return 0;
}

So when I compile it, the line marked as "Compile Error" provides an error in g++ 4.9:

main.cpp: In function ‘int main()’:
main.cpp:14:10: error: could not convert ‘x’ from ‘Class2 (*)(Class1 (*)())’ to ‘Class2’
    func(x);
          ^

clang++ 3.4.1 provides a similar error.

My best guess is that it thinks that "x" is some sort of function that returns a Class2, instead of a Class2 itself, but...why is this happening? I would think that the call to Class1 returns some anonymous Class1 which is passed into Class2's constructor.


Solution

  • Class2 x(Class1()); is a function declaration due to a vexing parse (google skills come in handy here).

    Alternative:

    Class2 x((Class1()));
    Class2 x{Class1()};