27

In-class initializers (C++11 feature) must be enclosed in curly braces or follow a = sign. They may not be specified inside parenthesis.

What is the reason for this?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
7cows
  • 4,974
  • 6
  • 25
  • 30

1 Answers1

42

I am not 100% positive about this, but this might be to prevent a syntax ambiguity. For example, consider the following class:

class BadTimes {
    struct Overloaded;
    int Overloaded;            // Legal, but a very strange idea.

    int confusing(Overloaded); // <-- This line
};

What does the indicated line mean? As written, this is a declaration of a member function named confusing that accepts as a parameter an object of type Overloaded (whose name isn't specified in the function declaration) and returns an int. If C++11 were to allow initializers to use parentheses, this would be ambiguous, because it could also be a definition of a member of type int named confusing that is initialized to the value of the data member Overloaded. (This is related to the current issue with the Most Vexing Parse.)

By requiring curly braces, this ambiguity is removed:

class BadTimes {
    struct Overloaded;
    int Overloaded;            // Legal, but a very strange idea.

    int confusing{Overloaded}; // <-- This line
};

Now, it's clear that confusing is actually an int initialized to the value of Overloaded, because there's no way to read it as a function declaration.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 1
    This makes sense to me, but we already have this confusion in a function body for example. Why should it be different here? – Rakete1111 May 10 '18 at 09:29
  • @Rakete111 In a function body, IIRC because of the Most Vexing Parse the statement `int confusing(Overloaded)` would be treated as a function prototype rather than a variable declaration, so I think the behavior is consistent. The use of parentheses for initialization is historical and there new brace-based initializers were in part designed to avoid the ambiguities of older syntax. – templatetypedef May 10 '18 at 15:18
  • There is no ambiguity, in all your described cases `Overloaded` refers to the `int`, and no vexing parse occurs. This doesn't answer the question IMO – Passer By May 12 '18 at 21:51