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?
That scope isn't global - static members are at class scope, and so their initialization expression is also at class scope.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With