c++static-membersmember-initialization

"Invalid use of non-static data member" when initializing static member from global variable


class A {
    int x;
    static int i;
};


int x = 10;
int A::i = x;

When I compile the code above, it get the error

<source>:8:12: error: invalid use of non-static data member 'A::x'
    8 | int A::i = x;
      |            ^
<source>:2:9: note: declared here
    2 |     int x;
      |         ^

What's causing this error?


Solution

  • This is a peculiar language quirk - the scope resolution on the left, in int A::i, affects the lookup scope on the right, so that actually refers to the x member of A.

    Either rename one of the variables, or specify the scope of the desired x explicitly:

    int A::i = ::x;