-1

code:

struct example
{
    int a = 0;   // line 3
    example()
    {}
};

I am gettting data initializer is not allowed here error at Line 3

How to solve this?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
raghu121
  • 13
  • 3
  • Use C++11 or newer and it should be fine. – Ted Lyngmo May 23 '21 at 15:26
  • That is not a declaration, it is an initialization. `struct example ex = { .a = 0.};` And in case a is meant to be a constant, use enum. –  May 23 '21 at 15:34
  • 1
    @wired Designated initializers didn't appear until C++20 and you don't need `struct` to instantiate a `class`. Initializing an `int` with a `double` also seems odd. – Ted Lyngmo May 23 '21 at 15:37
  • You may need to explain that point more, @wired . I'm not sure where you're going with it and as worded, I read it as incorrect. – user4581301 May 23 '21 at 15:38
  • How to set the Standard used by [Visual Studio Compiler](https://learn.microsoft.com/en-us/cpp/build/reference/std-specify-language-standard-version?view=msvc-160). How to set it with G++ and related compilers: Add `-std=`. Eg `-std=c++11` – user4581301 May 23 '21 at 15:42
  • 1
    @Ted - the points a typo (was not meant to be a double). Thanks for your input regarding C++ Version, that I was not aware of. –  May 23 '21 at 16:14

2 Answers2

4

In C++ prior to C++11 standard, you cannot initialize value where you declare it, you have to do it with constructor:

struct example
{
//    int a = 0; NOT ALLOWED
    int a;
    example() : a (0) {} // preferred way
/*  NOT PREFERRED WAY
    example() {
        a = 0;
    }
*/
}

EDIT: Thank to @user4581301 for the comments:

Here is initialization list

Here is why is initialization list preferred

1

How to solve this?

A few options:

  • Upgrade to C++11 (or later), where default member initialisers are were introduced to the language.
  • Or don't use default member initialisers. You can either:
    • Initialise in the member initialisation list of the constructor
    • Or don't use a constructor and use aggregate initialisation instead.
eerorika
  • 232,697
  • 12
  • 197
  • 326