Home c++ Type specifier required: nested classes. C++

Type specifier required: nested classes. C++




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

class rage
  rage () {}
  class test
    test (int y) {}
  test heythere (5); // & lt; - Error here
int main ()

Visual Studio yells about an error in the line test heythere (5); , underlines 5 and says that a type specifier is required, but that doesn’t tell me much.

Answer 1, authority 100%

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 a field directly in the class body, you must use either =… or {…} .

(…) – not allowed. Apparently because in this case it becomes too difficult for the compiler to distinguish between a field declaration with an initializer and a method declaration (where the parentheses would be a parameter list).

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 do, your choice is:

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

In this particular case, all five behave exactly the same, but in general there is a difference between them. More details 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) {...} . (Or : heythere {5} .)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions