#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?
#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?
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.