2

Lets say I have the following class:

class Foo
{
public:
    Foo() = { std::cout << "Hello world!" << std::endl; }
}

In the main function I call the following:

int main()
{
    Foo bar1(); // This doesn't echo "Hello World!"
    Foo bar2 = Foo(); // This does echo "Hello World!"
}

I don't understand why this would be occurring?

  • 10
    `Foo bar1();` declares a function – Piotr Skotnicki Nov 19 '18 at 21:15
  • 2
    Ah yeah, this is called "most vexing parse", I believe. – zzxyz Nov 19 '18 at 21:17
  • Use `Foo bar1;` with no brackets or `Foo bar1{};` with curly brackets – Killzone Kid Nov 19 '18 at 21:19
  • Thank you @zzxyz Makes perfect sense looking into the principle. – Alex Neumann Nov 19 '18 at 21:20
  • https://stackoverflow.com/questions/14077608/what-is-the-purpose-of-the-most-vexing-parse – BartoszKP Nov 19 '18 at 21:21
  • 1
    For future reference, this really isn't a MVP (but is probably the most inaccurately cited example of one, people just assume it is). The V in MVP likewise involves a function decl, but is considerably more counter-intuitive: `Type id( Type2() );` The linked question from BartoszKP cites the specific standard location where this is called out. It's considerably more brain food than the simple no-arg function decl you have here, so much so the standard specifically calls it out. – WhozCraig Nov 19 '18 at 21:26
  • Thanks, @WhozCraig - Although after reading, I consider the most vexing parse less vexing than this one :) – zzxyz Nov 19 '18 at 21:33

0 Answers0