Search code examples
c++singletonprivate-members

Singleton initialization


I implemented the Singleton design pattern in my code.

Suppose it is:

class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};

What puzzles me is the 'initialization' of this pattern. In the .cpp I put:

SingletonPointer* SingletonClass::s (0);

But I don't understand how is it possible to access define s, as it is private. How's that possible?

TIA, Jir


Solution

  • Static fields must have definitions besides their declaration. The declaration usually goes in the class declaration in the .h file, while the definition almost always goes in the .cpp file. The definition of static variables is a must, since they must be initialized to something.

    But even though the definition is outside of the class body and even in an entirely different file, it doesn't mean it's not a part of the class. The SingletonClass:: makes it part of the class definition (as opposed to the class declaration), and therefore it can 'access' private fields.

    The same goes for methods defined outside of the class body, for instance:

    // A.h
    class A
    {
    private:
        int b;
    public:
        A(int x) : b(x)
        {}
    
        Do();
    }
    
    // A.cpp
    A::Do()
    {
        return b;
    }