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

1

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?

Tierza answered 7/2, 2022 at 10:1 Comment(1)
did you research this error yourself, e.g. in google? what have you learned?Structure
R
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;
Rollandrollaway answered 7/2, 2022 at 10:7 Comment(4)
Could you please give a reference to the standard?Gigantes
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.Rogozen
@Gigantes eel.is/c++draft/basic.scope.class#1Rogozen
Probably best to use the scope operator to avoid an innocent-looking addition of a variable to A breaking the code.Osmious

© 2022 - 2025 — McMap. All rights reserved.