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?
The third line is parsed as declaring a function that takes no argument and returns a Foo
.
Foo f3();
declares a function called f3
, with a return type of Foo
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With