Most vexing parse


The most vexing parse is a specific form of syntactic ambiguity resolution in the C++ programming language. The term was used by Scott Meyers in Effective STL. It is formally defined in section 8.2 of the C++ language standard.

Example with classes

An example is:

class Timer ;
class TimeKeeper ;
int main

The line

TimeKeeper time_keeper);

is seemingly ambiguous, since it could be interpreted either as
  1. a variable definition for variable of class, initialized with an anonymous instance of class or
  2. a function declaration for a function that returns an object of type and has a single parameter that is a pointer to function returning an object of type .
Most programmers expect the first, but the C++ standard requires it to be interpreted as the second.
For example, g++ gives the following error message:

$ g++ -c time_keeper.cc
time_keeper.cc: In function ‘int main’:
time_keeper.cc:15: error: request for member ‘get_time’ in ‘time_keeper’, which is
of non-class type ‘TimeKeeper)’

Notice that the compiler gives the error message about the return statement of : since it interpreted the declaration of as a function declaration we won't be able to call the member function on this.
Clang++ provides a warning:
$ clang++ time_keeper.cc
timekeeper.cc:14:25: parentheses were disambiguated as a function declaration
'
TimeKeeper time_keeper);
'
timekeeper.cc:14:26: note: add a pair of parentheses to declare a variable
TimeKeeper time_keeper);


timekeeper.cc:15:21: member reference base type 'TimeKeeper )' is not a
structure or union
return time_keeper.get_time;

The common ways to force the compiler to consider this as a variable definition are:
TimeKeeper time_keeper);
TimeKeeper time_keeper = TimeKeeper);
TimeKeeper time_keeper;
TimeKeeper time_keeper;
TimeKeeper time_keeper;

Example with functions

An even simpler example appears when a functional cast is intended to convert an expression for initializing a variable or passing to a constructor parameter

void f

In this case, the parentheses around adouble are superfluous and the declaration of i is again a function declaration equivalent to the following

// takes an integer and returns an integer
int i;

To disambiguate this in favour of a variable declaration, the same technique can be used as for the first case above. Another solution is to use the cast notation:

// declares a variable called 'i'
int i;

Or also to use a named cast:

// declares a variable called 'i'
int i;

Uniform initialization syntax

Using the new uniform initialization syntax introduced in C++11 solves this issue.
The problematic code is then unambiguous when braces are used:

TimeKeeper time_keeper;

Using braces as above creates a variable definition for variable of class, initialized with an anonymous instance of class.