11

Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

Lets have this code

class Foo {
  Foo(int) { }
};

Then we have there results:

int main() {
  Foo f1 = Foo(5); // 1: OK, explicit call
  Foo f2(5); // 2: OK, implicit call
  Foo f3(); // 3: no error, "f3 is a non-class type Foo()", how so?
  Foo f4(f1); // 4: OK, implicit call to default copy constructor
  Foo f5; // 5: expected error: empty constructor missing
}

Can you explain what's happening in case 3?

Community
  • 1
  • 1
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • 13
    search: vexing parse – Nim Dec 12 '11 at 14:31
  • @Nim: Should have been an answer. – Björn Pollex Dec 12 '11 at 14:33
  • Also note that example 5 is doing what expected example 3 to do and calls the default constructor. – Joe Dec 12 '11 at 14:33
  • @BjörnPollex, recently, I've taken up commenting with appropriate search terms - sometimes, it's just a matter of missing terminology, and the OP can then discover for themselves.. :) anyways, I knew someone would come in quicker with a real answer.. ;) – Nim Dec 12 '11 at 14:36

6 Answers6

12

The third line is parsed as declaring a function that takes no argument and returns a Foo.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
8

Foo f3(); declares a function called f3, with a return type of Foo.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
5

C++ has a rule that if a statement can be interpreted as a function declaration, it is interpreted in this way.

Hence the syntax Foo f3(); actually declares a function which takes no arguments and returns Foo. Work this around by writing Foo f3;, it will call the default constructor too (if there is one, of course).

Kos
  • 70,399
  • 25
  • 169
  • 233
4
  • f1 invokes the copy constructor after an explicit call, you were wrong on this one
  • f2 is an explicit constructor call // you were wrong here too
  • f3 declares a function
  • f4 is again the copy constructor, like f1 // you're right here
  • f5 would calls the default constructor // you're right here again
Xeo
  • 129,499
  • 52
  • 291
  • 397
3

This isn't what you think it is:

 Foo f3();

You may think this is an explicit call of the default constructor, but it's not. It's actually a declaration of a function named f3 which takes no parameters and returns a Foo by value.

That this is parsed as a function declaration rather than a constructor call is known as the Most Vexing Parse.

John Dibling
  • 99,718
  • 31
  • 186
  • 324
2

You've defined a function called f3 that returns a foo in case 3. In case 5, you have no default constructor defined, so you get an error.

MGZero
  • 5,812
  • 5
  • 29
  • 46