user2991252 user2991252 - 11 months ago 113
C++ Question

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

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;


Answer Source

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).