Home >Backend Development >C++ >Why Don't C 11 In-Class Initializers Allow Parentheses?

Why Don't C 11 In-Class Initializers Allow Parentheses?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 05:55:09166browse

Why Don't C  11 In-Class Initializers Allow Parentheses?

Ambiguity in Class Initializers: The Role of Braces and Equals

In C 11, in-class member initializers can only be defined using curly braces ({}) or the equals sign (=). This restriction raises the question of why parentheses are not allowed for this purpose.

One primary reason for this limitation lies in the potential for syntax ambiguity. Consider the following class:

class BadTimes {
public:
    struct Overloaded;
    int Overloaded;            // Data member

    int confusing(Overloaded); // Function declaration
};

If parentheses were allowed for initializers, the line "int confusing(Overloaded);" could be ambiguous. It could be interpreted either as a function declaration (as shown above) or as a member variable initialization if parentheses were used for the initializer:

int confusing{Overloaded};

To eliminate this ambiguity, curly braces or the equals sign are required. This ensures that there is no confusion between member variable initializers and function declarations:

class BadTimes {
public:
    struct Overloaded;
    int Overloaded;

    int confusing{Overloaded}; // Member variable initialized with Overloaded
};

The above is the detailed content of Why Don't C 11 In-Class Initializers Allow Parentheses?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn