-
July 23rd, 2009, 06:11 AM
#1
Singleton class and static data members of the class type
Hi : )
Last night a had a really hard time trying to understand the singleton pattern for a class which has a data member, with the same type as the class itself:
Code:
class Singleton
{
public:
void printData() { cout << data << endl;}
private:
Singleton(): data(0) { /* other work */ }
Singleton( const Singleton &); // never defined
Singleton & operator=( const Singleton &); // never defined
~Singleton();
int data;
static Singleton singleton;
};
Ok, so, now I want to be able to use object singleton as a regular object - a want to have access to its public data members from outside the class scope. Let's just say that I prefer to use an object of type Singleton, rather than a pointer to a Singleton object.
This code, as it is compiles fine, but singleton(the static object) is never created ( i think..)
I suppose, as any other static data member, singleton must be defined exactly once outside the class body. How do I do that with a private constructor?
I suppose I should define a public static function that:
1. creates dynamically an object if there is no object created
2.returns a reference to it..
Basically my question is:
If i define only one constructor that is private, how can I initialize the class static member, which is an object of the same type as the class itself outside the class definition?
It's all very confusing...
Last edited by seventhirty; July 23rd, 2009 at 06:27 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|