1

Why does this work

auto f = std::string();
f = "src.Id";

But this does not

std::string f();
f = "src.Id";
jeohd
  • 309
  • 1
  • 2
  • 11
  • 2
    Lookup "the most vexing parse" in C++. – R Sahu Feb 17 '18 at 06:14
  • I wish people wouldn't call this simple case *the most vexing parse*. This is the most vexing parse https://en.wikipedia.org/wiki/Most_vexing_parse. – john Feb 17 '18 at 06:16
  • Arguably, whichever vexing parse you're experiencing at the moment is the most vexing parse. :) – Retired Ninja Feb 17 '18 at 06:28
  • If you use the newer syntax `std::string f{};`, it won't consider `f` a declaration of a function returning `std::string`. – Tony Delroy Feb 17 '18 at 06:40
  • 1
    @john: perhaps you should correct Scott Meyers (who invented the term) - see his comment *"Widget w3(); // most vexing parse! declares a function!"* [here](http://scottmeyers.blogspot.jp/2015/09/thoughts-on-vagaries-of-c-initialization.html). Just because WIkipedia only lists a more complex example doesn't mean the simpler example isn't also covered by the term. – Tony Delroy Feb 17 '18 at 06:46
  • @TonyDelroy That's interesting but I fail to see how the two cases are related. The more complex case really is much more vexing, it takes much more knowledge to understand what's going on. The OP's case is easy once you've had it explained. Scott Meyers original example was the complex case. Why call two different things with the same name? – john Feb 17 '18 at 07:06
  • @john: because the fundamental issue is the same... *with or without arguments*, the language assumes a function declaration where it would otherwise be ambiguous and the programmer may have intended a default-constructed variable. – Tony Delroy Feb 17 '18 at 09:51

1 Answers1

1

It's because

std::string f();

declares a function f which takes no arguments and returns a string. It's often (but wrongly) called the most vexing parse.

john
  • 85,011
  • 4
  • 57
  • 81