6

There is a strange behavior when I compile the below code:

class Foo {
};
int main() {
    Foo(b);
}

It compiles successfully even without declaration of b. Any explanation for this?

Boann
  • 48,794
  • 16
  • 117
  • 146
Sarvesh
  • 153
  • 4

1 Answers1

10

It's a declaration itself. It declares a variable named b with type Foo, i.e. the same effect as Foo b;.

[stmt.ambig]/1

There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.

and [stmt.ambig]/2

The remaining cases are declarations. [ Example:

class T {
  // ...
public:
  T();
  T(int);
  T(int, int);
};
T(a);               //  declaration

...

songyuanyao
  • 169,198
  • 16
  • 310
  • 405