c++ - class static member function chosen over global function with same name? -


doubt originated here


int g() {    cout << "in function g()" << endl;    return 0; }  class x { public:   static int g() {      cout << "in static member function x::g()" << endl;      return 1;   } };  class y: public x {    public:   static int i; };  int y::i = g();    

initially though symbol resolution happens inner scope outer scope, why x::g() called.
closely noticed code

int y::i = g(); 

how able access x::g() without namescope?
, scope in statement lies should global, not y:: or x:: , symbol resolution should give global version of function g()?

note: think earlier answer wrong. not koenig lookup i.e argument-dependent name lookup (adl). deleted (earlier) answer since found relevant section standard answers question.

your code directly section §9.4/2 of c++03 standard.

a static member may referred directly in scope of class or in scope of class derived (clause 10) class; in case, static member referred if qualified-id expression used, nested-name-specifier of qualified-id naming class scope static member referenced.

it gives example (which you've asked in question)

[example:      int g();     struct x {         static int g();     };     struct y : x {         static int i;     };     int y::i = g(); // equivalent y::g();  —end example] 

it says in §9.4/3

if unqualified-id (5.1) used in definition of static member following member’s declarator-id, , name lookup (3.4.1) finds unqualified-id refers static member, enumerator, or nested type of member’s class (or of base class of member’s class), unqualified-id transformed qualified-id expression in nested-name-specifier names class scope member referenced.

since happens only in definition of static member, means y::g() called in initialization, not in assignment:

//definition-cum-initialization int y::i = g(); // equivalent y::g(); int main() {    //assignment     y::i = g(); // not equivalent y::g(); calls global g() } 

see output here : http://www.ideone.com/6kdmi

lets consider example:

struct b{};  b f();  namespace ns  {    struct { static b b;};    b f(); }  //definition cum initialization b ns::a::b = f();  //calls ns::f() b b = f();         //calls global f()  int main()  {    //assignment    ns::a::b = f(); //calls global f()    b = f();        //calls global f() } 

see complete demo here : http://www.ideone.com/53how


Comments