2

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.

David Heffernan
  • 587,191
  • 41
  • 1,025
  • 1,442
Hounddog
  • 325
  • 1
  • 10

2 Answers2

4

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()};
Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
  • Awesome! In 11 minutes when the accept button unlocks, I'll accept this answer. Thanks for your help! I hadn't heard of "vexing parse" before, and without that specific term, googling for a solution was a bit difficult :-) Thanks again. – Hounddog May 16 '14 at 13:48
2

This is because this line

Class2 x( Class1());

declares a function actually and not an object. This is known as vexing parse. To avoid this issue you should write:

Class2 x((Class1()));

or

Class1 y;
Class2 x( y);
4pie0
  • 28,488
  • 8
  • 76
  • 116