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?

1
  • did you research this error yourself, e.g. in google? what have you learned?
    – jasie
    Commented Mar 1, 2022 at 7:34

1 Answer 1

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;
4
  • Could you please give a reference to the standard?
    – Evg
    Commented Feb 7, 2022 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
    Commented Feb 7, 2022 at 19:19
  • 1
    @Evg eel.is/c++draft/basic.scope.class#1
    – Brian Bi
    Commented Feb 7, 2022 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
    Commented Feb 16, 2022 at 16:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.