Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: non-static data member initializers - c++

Tags:

c++

static

I made the following program in c++ and got a compilation warning:

 warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]

what does it mean?

 struct struct1 {
   int i = 10;
 };

 int main() {
   struct1 s1;
   cout << s1.i;
   return 0;

 }
like image 269
user2991252 Avatar asked Feb 17 '26 23:02

user2991252


1 Answers

A static data initializer is an initializer that is done outside the scope of the class. In this case, it refers to the inline initialization you did with int i = 10;. However, this code would also not like it if you did:

struct struct1 {
    int i;
};
int struct1::i=10;

In this case, you are initializing i as if all struct1's shared i, but they each have their own.

In older versions of C++, the only way to get around this is to initialize the value in the constructor:

struct struct1 {
    int i;
    struct1(): i(10) {}
};

In C++11, the standards committee decided to allow people to initialize values the way you want to, presumably to avoid this confusion (though I'm not privy to such things).

like image 84
IdeaHat Avatar answered Feb 19 '26 14:02

IdeaHat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!