0

A strange C++ compiler behavior caught me by surprise today.

class Foo {
    friend ostream& operator << (ostream& os, const Foo& rhs)
    {
       return os << sizeof(rhs) <<  endl;
    }
};

struct Bar { };

int main()
{
    Foo f(Bar());
    cout << f;
    return 0;
}

Apparantly, the code above compiled fine, even though there was no

Foo(const Bar&); 

c'tor defined. Compiling with -Wall showed that the compiler interprets the expression

Foo f(Bar());

as a prototype for a function

Foo f(Bar (*)())

instead of an expression for creating an object of type Foo.

What really is the catch (rule) here??

Rajat
  • 467
  • 1
  • 5
  • 15

1 Answers1

1
Foo f(Bar());

Here compiler is assuming is to be a function call as a result of C++ "most vexing parse".

What you can do is just put one more parenthesis around your object.

Foo f((Bar()));

If you see C++11 documentation there are more ways to avoid this behavior.

ravi
  • 10,994
  • 1
  • 18
  • 36