-1
#include <fstream>
#include <iostream>

class Bar { };

class Foo {
    public:
    Foo(Bar&) { }
 };

int main()
{
   Foo bar(Bar());
}

What does Bar() return, and why does this code compile?

Martin G
  • 17,357
  • 9
  • 82
  • 98

1 Answers1

1

It actually doesn't matter what Bar() returns because it actually doesn't do anything! The statement

Foo bar(Bar());

is a function declaration, declaring the function bar which returns a Foo and takes a function taking no argument and return a Bar as argument. This kind of declaration is known as Most Vexing Parse.

Assuming the statement were written as as

Foo bar{Bar()};

the expression Bar() would create a temporary object of type Bar by calling Bar's default constructor. Of course, the code wouldn't compile because you can't bind the temporary produced by Bar() to a non-const lvalue reference which is what Foo's constructor expects.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380