Search code examples
c++constructorinitializer

Initialising in-class member with constructor arguments with round ( ) brackets?


I'm sorry, I haven't programmed C++ in a while, I'd like to refresh my knowledge about what exact rule I'm violating here:

I can do:

int main()
{
    int a(5);
}

but cannot do:

struct Foo
{
    int a(5); // Error: expected a type specifier / Error: syntax error, 'constant'
}

I am trying to regain some lost knowledge, can someone direct me to the rule that disallows this? I'm pretty sure there'd be a question about it on here, I couldn't find it. The only thing I remember is that the committee debated (for C++11 I think) in class constructor arguments and introduced new squiggly bracket constructor initialisers, like int a{5}; but I would like to know why int a(5); isn't allowed inside a class. Has this always been disallowed in C++?


Solution

  • A species of vexing parse. Names in default member initializers are supposed to be looked up in the completed class, because they are suppose to imitate constructor initializers. With (), the compiler won't be able to figure out what it's parsing, because it can refer to things declared later in the class:

    struct X {
        int f(x); // function or data member?
        static const int x = 1;
    };