When attempting to initialize a member of a class that is an object of a nested class, an error occurs. Here is the code:

class rage { public: rage() { } private: class test { public: test(int y) { } }; test heythere(5); // <-- Ошибка тут }; int main() { } 

Visual Studio shouts an error in the test heythere(5); , underlines 5 and says that a type specifier is required, but this is not enough for me to say.

  • Moreover, if this were a non-nested class, then the constructor works fine .. - escape
  • In fact, a duplicate: www.stackoverflow.com/questions/928530/… Only that question is overloaded with details that it will be difficult for the novice to wade through. - AnT

1 answer 1

 test heythere(5); 

main.cpp: 31: 19: error: expected identifier before numeric constant
main.cpp: 31: 19: error: expected ',' or '...' before numeric constant

If you initialize the field directly in the class body, you must use either = … or {…} .

(…) - it is impossible. This is probably because in such a case it becomes too difficult for the compiler to distinguish the declaration of the field with the initializer from the declaration of the method (where the brackets would be a list of parameters).

Even the name of such an initializer in the grammar of the language hints at this: brace-or-equal-initializer .

One of the following options will suit your choice:

 test heythere = 5; test heythere = test(5); test heythere{5}; test heythere = {5}; test heythere = test{5}; 

Specifically, in this case, all five behave in exactly the same way, but in general there is a difference between them. Read more here: https://en.cppreference.com/w/cpp/language/initialization

Another option: Leave only test heythere; , and perform initialization in the initialization list in the constructor: rage() : heythere(5) {...} . (Either : heythere{5} .)

  • one
    Thanks, helped) I myself would not understand exactly, because this is a special case, as I understand it - escape
  • This is not a special case, but a very ordinary one (normal). - AR Hovsepyan