Class static variable initialization order

  • A+

I have a class A which has two static variables. I'd like to initialize one with another, unrelated static variable, just like this:

#include <iostream> class A { public:     static int a;     static int b; };  int A::a = 200; int a = 100; int A::b = a; int main(int argc, char* argv[]) {     std::cout << A::b << std::endl;      return 0; } 

The output is 200. So, could anyone tell me why?


That's correct according to the lookup rules. [basic.lookup.unqual]/13 says:

A name used in the definition of a static data member of class X (after the qualified-id of the static member) is looked up as if the name was used in a member function of X. [ Note: [] further describes the restrictions on the use of names in the definition of a static data member.  — end note ]

Since the unqualified a is looked up as if you are inside a member function, it must find the member A::a first. The initialization order of A::a and A::b doesn't affect the lookup, though it affects how well defined the result is.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: