Why can't a data class be initialized with direct initialization syntax?

I'm curious to know why class members cannot be initialized using () syntax? Consider the following example:

#include <iostream> class test { public: void fun() { int a(3); std::cout<<a<<'\n'; } private: int s(3); // Compiler error why??? }; int main() { test t; t.fun(); return 0; } 

The program does not work in compilation and gives the following errors.

 11 9 [Error] expected identifier before numeric constant 11 9 [Error] expected ',' or '...' before numeric constant 

Why? What is the reason? What does the C ++ standard say about initializing class data members? Your help is greatly appreciated. thanks

+5
source share
1 answer

Early suggestions leading to the introduction of a function explain that problems with analysis should be avoided .

Here is just one of the examples presented here:

Unfortunately, this makes the initializers of the form ( expression-list ) "ambiguous at the time of parsing the declaration:

 struct S { int i(x); // data member with initializer // ... static int x; }; struct T { int i(x); // member function declaration // ... typedef int x; }; 

One possible solution is to rely on an existing rule, which, if the declaration can be an object or function, then its function:

 struct S { int i(j); // ill-formed...parsed as a member function, // type j looked up but not found // ... static int j; }; 

A similar solution would be to apply another existing rule, which is currently used only in templates, if T can be a type or something else, then it is something else; and we can use " typename " if we really mean the type:

 struct S { int i(x); // unabmiguously a data member int j(typename y); // unabmiguously a member function }; 

Both of these solutions introduce subtleties that many users may not understand (as many questions about comp.lang.C ++ testify to why “ int i(); ” in the block area does not declare default initialization int ).

The solution proposed in this article is to allow only initializers of the forms " = initializer-clause" and " { initializer-list } ". This solves the ambiguity problem in most cases. [..]

+11
source

Source: https://habr.com/ru/post/1214075/


All Articles