Reputation: 83
When x is a global variable as well as a static variable in class while defining the static member of class, ambiguity as below is seen.
ambiguity.cpp
using namespace std;
int z = 100;
int x = 100;
class WithStatic {
static int x;
static int y;
static int a;
public:
void print() const {
cout << "WithStatic::x = " << x << endl;
cout << "WithStatic::y = " << y << endl;
cout << "WithStatic::a = " << a << endl;
}
};
int WithStatic::x = 1;
int WithStatic::y = x + 1;
int WithStatic::a= z+1;
int main() {
WithStatic ws;
ws.print();
}
Output:
WithStatic::x = 1
WithStatic::y = 2
WithStatic::a = 101
I have a problem at defining y
. Why is global x
not taken instead? WithStatic::x
is taken.
Why is the output of y not equal to 101 , instead of 2?
Upvotes: 0
Views: 68
Reputation: 264361
Paragraph 3:
A static member may be referred to directly in the scope of its class or in the scope of a class derived (Clause 10) from its class; in this case, the static member is referred to as if a qualified-id expression was used, with the nested-name-specifier of the qualified-id naming the class scope from which the static member is referenced.
// Example:
int g();
struct X
{
static int g();
};
struct Y : X
{
static int i;
};
int Y::i = g(); // equivalent to Y::g();
Upvotes: 4