2

One of the Question on C++ FAQ discusses correct way to declare local object within a function: http://www.parashift.com/c++-faq/fn-decl-vs-obj-instantiation.html

Given example from FAQ:

class Bar { 
public: 
  Bar();
};

class Foo {
public:
  Foo(Bar const& b);
  void blah();
};

void yourCode()
{
  Foo x(Bar());  // error     
}

In VS2012, error is Foo x(Bar (__cdecl *)(void))': prototyped function not called (was a variable definition intended?)

Could someone explain me why this this declaration gives an error ?(C++ FAQ explanation is too vague). Foo and Bar are both visible within body of yourCode(), and Foo x(Bar()); is a way I would declare an object of type Foo.

newprint
  • 6,936
  • 13
  • 67
  • 109

2 Answers2

6

As this C++'s the most vexing parse, you can do:

Foo x((Bar()));

or

Foo x = Bar();

The details are reviewed in the very parashift link you provided in your question.
Note though, the second example will break if the Foo copy constructor is made explicit.

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
0

It looks like you've got a const consistency problem. The constructor for Foo wants a const Bar which Bar() isn't. Try:

const Bar b = Bar();
Foo x = Foo(b);
Paul Evans
  • 27,315
  • 3
  • 37
  • 54