4

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

I have seen the C++ FQA entries about nested constructor calls and bracing and always wondered how C++ parsers resolve two and why it isn't possible for parsers to resolve it.

So I get why foo xxx(); is ambiguous. but what makes then foo x(bar()); ambiguous, as it is clearly no forward-declaration. (i.e.: there should be a grammar that can successfully detect this).

Could someone explain the limitations and ambiguity in that part of the C++ grammar?

Community
  • 1
  • 1
Alexander Oh
  • 24,223
  • 14
  • 73
  • 76

2 Answers2

7
foo x(bar());

This could be either:

1) A declaration for a variable called x whose value is a default-constructed bar. This is the same as foo x = bar();.

2) A declaration for a function called x that returns foo and takes a single parameter -- a function that returns a bar and takes no parameters. This is the same as foo x(bar (void));

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • that is my point here isn't 2 an invalid declaration? or what does it mean? does it mean then that bar is a function prototype and foo takes a function pointer as first argument? shouldn't that be bar (*)() then? – Alexander Oh Jul 13 '12 at 20:35
  • 3
    No, 2 isn't an invalid declaration. `foo x(bar (void))` means that `x` is a function that returns `foo` and takes `bar (*)(void)`. The reason the `(*)` doesn't have to be explicit is that there's a rule for function declarations that if a parameter type is a function type then the parameter is 'adjusted' to be a pointer to that function type. This is exactly like the rule where if a parameter is an array it is 'adjusted' to be a pointer type; `void a(int x[])` is exactly equivalent to `void a(int *x)`, and `foo x(bar())` is equivalent to `foo x(bar(*)())`. – bames53 Jul 13 '12 at 20:49
4

The C++ FQA is a pile of garbage. Ignore it.

As for foo x(bar()), it is as ambiguous as foo x(), except the type of x also takes an argument, which is a function. Add a pointer here and you'll see what I mean.

foo (*x)();
foo (*x)(bar(*)());

Even the idea of allowing this is beyond silly, but nobody can change it now.

(I have a sneaking suspicion that this grammar is a tad off, but I'm sure someone will correct me).

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 1
    I don't think `x` is a function pointer here, just a function declaration that decays to a pointer when used. – Xeo Jul 13 '12 at 20:25
  • It isn't, I'm just adding the pointer to make it more obvious how it's equivalent. – Puppy Jul 13 '12 at 20:28