Monday, May 5, 2008

Scope Jumble


What's the value of X::i?

int g() { return 23;}
struct X {
    static int g() { return 42; }
    static int i;
};
int X::i = g();

The answer is: 42 - says ISO C++ in section 9.4.2. The initialization of the static data member is implicit in the scope of the struct. Oh, yes! The standard's example is even more fun:

int g();
struct X {
        static int g();
};
struct Y : X {
        static int i;
};
int Y::i = g();         // equivalent to Y::g();

Note that X could be definied in another header file than g and the initialization normaly is in a cc-file. Find, Rover, find!
 
Thank you, Roker

No comments:

Post a Comment