Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ spooky constructor [duplicate]

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?

like image 762
Jan Turoň Avatar asked Dec 12 '11 14:12

Jan Turoň


3 Answers

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

like image 175
Björn Pollex Avatar answered Sep 27 '22 17:09

Björn Pollex


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

like image 30
Mike Seymour Avatar answered Sep 27 '22 19:09

Mike Seymour


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).

like image 26
Kos Avatar answered Sep 27 '22 17:09

Kos