The title of this site refers to a phrase coined by Scott Meyers. The most vexing parse is a result of the ambiguity of function declarations and variable definitions in C++, but I also think it’s a fun sequence of words.
You’ve probably run into this while trying to define a variable with a call to a default constructor. That happens
pretty frequently, so get in the habit of of doing so correctly: by omitting the empty parentheses, as in string str
rather than string str(). This is necessary because the latter is ambiguous:
string str(); // Ok, but ambiguous
str = "Hello World!"; // Error! str is not a string
string str2 = str(); // Ok, str is a function returning a string, defined elsewhere
The errors will look something like these:
error: assignment of function ‘std::string str()’
error: request for member ‘c_str’ in ‘str’, which is of non-class type ‘std::string()’
The C++ standard forces the compiler to treat such expressions as declarations1. In this scenario, the ambiguity can be resolved by removing the parentheses or by using an empty brace initializer (in C++ 11). There are other ways to arrive at an ambiguous expression, and I encourage you to check out Effective STL2 where Scott Meyers talks about some of them.
-
Meyers, S. (2001). Be alert for C++’s most vexing parse. In Effective STL (pp. 33–35). Addison-Wesley. ↩︎