Home >Backend Development >C++ >Why can\'t I initialize class data members in C using direct initialization syntax?
Programmers may wonder why class data members cannot be assigned values using direct initialization syntax, similar to how local variables can. Consider the following example:
class test { public: void fun() { int a(3); std::cout << a << '\n'; } private: int s(3); // Compiler error: Why??? };
When compiling this code, errors will occur:
11 9 [Error] expected identifier before numeric constant 11 9 [Error] expected ',' or '...' before numeric constant
Why does this happen? Let's review the C standard's stance on class data member initialization.
Early proposals for the direct initialization syntax explained that it was excluded to prevent parsing problems. For example, consider the following code:
struct S { int i(x); // data member with initializer // ... static int x; }; struct T { int i(x); // member function declaration // ... typedef int x; };
If direct initialization were allowed, parsing the declaration of struct S would become ambiguous. The compiler could interpret int i(x); either as a data member with an initializer or a member function declaration with a parameter.
One solution is to rely on the rule that if a declaration can be interpreted as both an object and a function, it should be treated as a function. However, this rule already exists for block-scoped declarations, leading to potential confusion:
struct S { int i(j); // ill-formed...parsed as a member function, // type j looked up but not found // ... static int j; };
Another solution is to use the rule that if a declaration can be interpreted as both a type and something else, it should be treated as the latter. Again, this rule already exists for templates:
struct S { int i(x); // unabmiguously a data member int j(typename y); // unabmiguously a member function };
However, both these solutions introduce subtleties that are prone to misunderstanding.
To address these ambiguities, the C standard proposed allowing only initializers of the following forms:
This solves the ambiguity in most cases and avoids the need for additional rules.
In summary, the prohibition of direct initialization syntax for class data members in C stems from parsing ambiguities that could arise during the declaration of complex data structures involving both data members and function declarations or type definitions with similar signatures.
The above is the detailed content of Why can\'t I initialize class data members in C using direct initialization syntax?. For more information, please follow other related articles on the PHP Chinese website!