Why does Foo(b) compile successfully in C++?

Sarvesh :

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?

songyuanyao :

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

...

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=375939&siteId=1