1

Why does the following not compile:

typedef int Table;

class FullObjId 
{
public:
    explicit FullObjId( const Table* i ) {}
};

class TableInfo 
{
public:
    TableInfo( const FullObjId& o ) {}
    bool isValid() { return true; }
};

void dataSourceForHist( const Table& table )
{
   // The next line gives an error
   TableInfo tableInfo( FullObjId( &table ) );
   // Unless it's written like this:
   //TableInfo tableInfo( ( FullObjId( &table ) ) );

   if (!tableInfo.isValid())
   {
      ...
   }
}

I have tried with the Intel Compiler 12.1 for Linux, and using http://gcc.godbolt.org/ with g++ 4.8, icc 13.0, clang 3.4.1. All the compilers I have tried give an error along the lines of:

error: request for member ‘isValid’ in ‘tableInfo’, which is of non-class type ‘TableInfo(FullObjId&)’
  • Does `TableInfo tableInfo(static_cast(&table));` work ? – Quentin Jun 04 '14 at 12:32
  • 2
    Because that line is declaring `tableInfo` as a *function* taking a parameter named `table` with type `FullObjId&` and returning `TableInfo`. There's a whole bunch of similar questions on SO, search for *most vexing parse*. This is valid, btw, and the error is coming from the expression in the `if` statement that follows it. – jrok Jun 04 '14 at 12:38

2 Answers2

0

The problem (also called most vexing parse) relies on the fact that:

TableInfo tableInfo( FullObjId( &table ) );

is interpreted as a function declaration.

Assuming you are using C++11, you should use:

TableInfo tableInfo{ FullObjId( &table ) };

Live demo

instead.

Alternatively you can add extra parenthesis (works on C++03):

TableInfo tableInfo( (FullObjId( &table )) );

Live demo

Shoe
  • 74,840
  • 36
  • 166
  • 272
0
TableInfo tableInfo( FullObjId( &table ) );

Declares tableInfo to be a function which takes a reference to FullObjId (the name of the parameter is table) and returns TableInfo. This is the so-called most vexing parse.

Workaround with C++11:

TableInfo tableInfo( FullObjId{&table} );
Columbo
  • 60,038
  • 8
  • 155
  • 203