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
Release: 2024-12-20 05:55:09
Original
166 people have browsed it

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
};
Copy after login

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};
Copy after login

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
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template