10

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?

torbatamas
  • 1,236
  • 1
  • 11
  • 21

3 Answers3

15

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

Puppy
  • 144,682
  • 38
  • 256
  • 465
10

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).

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
-2

This form of initialization of static members are not necessary in older c++. They are made compulsary in later release of c++.

And, this form of static member initialization will generally used to initialize the static members before creation of any class objects.

(E.g)  int MyClass::objectsCounter=0;

But by,

foo* foo::ref = new foo;

this statement you are just initializing a static member (which is of pointer type) by creating a new object.

And in this case you are intializing a private member by calling a private method of its own class.

Hence there is no role of globe scope here.

Muthu Ganapathy Nathan
  • 3,199
  • 16
  • 47
  • 77
  • -1 What are you referring to by "older" and "later" *releases* of C++? AFAIK, this has been part of the language design since the first standard in 1998. Moreover, using `new foo` always creates an object. The statement performs 2 things: a) an instance of type `foo` is created; and b) `foo::ref` is assigned a pointer to the newly allocated object. – André Caron Aug 31 '11 at 14:34
  • @André Caron Thanks for your comments.I edited my post. I actually meant to say this info only. But I wrongly delivered the information. Regarding older and later c++ :-, the info provided now is taken form THE COMPLETE REFERENCE-HERBERT. – Muthu Ganapathy Nathan Aug 31 '11 at 14:56
  • If you plan on professional C++ programming, you should consider using [C++ books recommended by the C++ community](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – André Caron Aug 31 '11 at 15:30