A constructor declaration may be surrounded by parentheses. What for?

[class.ctor] / 1

Constructors have no names. In the constructor declaration, declarator is the declarator of the function (8.3.5) of the form ptr-declarator (parameter-declaration-sentence) exception-specification opt attribute-specifier-seq opt , where the ptr-declarator consists exclusively of id-expression, optional attribute-specifier- seq and optional parentheses and id expression take one of the following forms: ...

And yes, this compiles:

struct S{ (S)() {} }; 

But why is this allowed?

+7
c ++
source share
1 answer

This is because the constructor is a function, and most declarations can be surrounded by brackets (even several):

 // all are valid! void ((a))(); // void a(); int (a); // int a; struct S { (S)(); // constructors (~S)(); // destructors }; 

See Why does C ++ allow us to surround a variable name in parentheses when declaring a variable? why it is allowed. This syntax was probably extended to constructors when they were defined.

0
source share

All Articles