Reputation: 3125
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
Upvotes: 1
Views: 15955
Reputation: 101446
The best way you can use the Singleton pattern is to not use it at all.
A brief summary of why Singletons are bad:
Using a Singleton doesn't solve any problem. It just applies false semantics to existing code, makes future extensions of that code difficult or impossible (what if you need two tomorrow?), and adds new problems. Long story short, just don't use them.
Upvotes: 6
Reputation: 1075
The private variables can be accessed by all methods of a class. The only place you are accessing the s variable is in method Get() which belongs to the same class.
If you want to access the s from outside, you can't do it directly, but you have to call the Get() method (which is public) and that method will actually return s for you.
Usage:
Singleton * s = SingletonClass::Get();
Upvotes: 2
Reputation: 6424
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;
}
Upvotes: 7
Reputation: 363497
It is accessed from the outside via Get
(if you give that the appropriate type). The fact that it is private
doesn't prevent that method from returning a pointer to it. A member being private
just prevents access to it by name.
Upvotes: 0
Reputation: 500167
In the initialization code, you're not accessing Singleton::s
, you're defining it.
Upvotes: 2