static scope question

There is something about static scope I am not understanding.
Please explain the following output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

class A
{
    public:
        static int i;                       //class A scope
};
int i = 1;                                  //global scope
int A::i = i;                               //initialize static variable

A a;

int main()
{                                           //output
    std::cout << "  i=" << i << std::endl;  //i=1
    std::cout << "a.i=" << a.i;             //a.i=0
}                               //expected    a.i=1 


output:
1
2
  i=1
a.i=0


Thank you.
Last edited on
closed account (SECMoG1T)
the problem is that int A::i is created before int i is created so A::i gets a default integral value
Nice question. In the initializer of a static member variable, class is in scope, so the "i" in int A::i = i; is the class member, not the global variable. It's just like in the body of a member function, "i" would refer to the class member even if the function is defined out of line.

Use
int A::i = ::i;

see http://en.cppreference.com/w/cpp/language/unqualified_lookup#Static_data_member_definition
Last edited on
Topic archived. No new replies allowed.