19
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?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
YuCL Lan
  • 193
  • 1
  • 5

1 Answers1

21

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;
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Could you please give a reference to the standard? – Evg Feb 07 '22 at 13:57
  • 3
    I wouldn't call this a peculiar language quirk. Imagine if `A::i` were a function being defined out of line, rather than a static data member. You would expect that, inside the body of the function, `x` would refer to `A::x`. It's just that when the same thing happens in a static data member definition, it's a little bit surprising because we're not used to it. – Brian Bi Feb 07 '22 at 19:19
  • 1
    @Evg http://eel.is/c++draft/basic.scope.class#1 – Brian Bi Feb 07 '22 at 19:20
  • Probably best to use the scope operator to avoid an innocent-looking addition of a variable to `A` breaking the code. – user904963 Feb 16 '22 at 16:41