Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I call the private constructor from ?global scope?

Tags:

c++

this code compiles and runs without errors:

class foo{
  static foo *ref;
  foo(){}
  public:
    static foo *getRef(){
      return ref;
    }
    void bar(){}
};

foo* foo::ref = new foo; // the construcrtor is private!

int main(int argc, const char *argv[])
{
  foo* f = foo::getRef();
  f->bar();
  return 0;
}

could somebody explain why can the constructor be called?

like image 387
torbatamas Avatar asked Aug 31 '11 14:08

torbatamas


2 Answers

That scope isn't global - static members are at class scope, and so their initialization expression is also at class scope.

like image 58
Puppy Avatar answered Nov 05 '22 18:11

Puppy


The answer is that it is not available in the global scope. The initializer of a static member is defined to be inside the class scope, so it has access to the private members.

§9.4.2/2 [...]The initializer expression in the definition of a static data member is in the scope of its class (3.3.6).

like image 45
David Rodríguez - dribeas Avatar answered Nov 05 '22 20:11

David Rodríguez - dribeas