Click here to Skip to main content
15,881,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,


In Singleton class why we need static method?

Please find the below example:

C++
#include<iostream>

using namespace std;

class Singleton
{
private:
    static bool instanceFlag;
    static Singleton *single;
    Singleton()
    {
        //private constructor
    }
public:
    static Singleton* getInstance();
    void method();
    ~Singleton()
    {
        instanceFlag = false;
    }
};

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
    if(! instanceFlag)
    {
        single = new Singleton();
        instanceFlag = true;
        return single;
    }
    else
    {
        return single;
    }
}

void Singleton::method()
{
    cout << "Method of the singleton class" << endl;
}

int main()
{
    Singleton *sc1,*sc2;
    sc1 = Singleton::getInstance();
    sc1->method();
    sc2 = Singleton::getInstance();
    sc2->method();

    return 0;
}


Regards,
Ranjith
Posted
Updated 18-Oct-13 2:07am
v2
Comments
Timberbird 18-Oct-13 8:12am    
Because we are not able to create class instance in any other way - its constructor is private and therefore closed to "outer world". Static method belonging to the same class, hovewer, can access its constructor and create a class instance. Is this a test?

1 solution

If the getInstance() were not static you could only call it for an object of the class. But at the time you call it you typically have no object of that class; instead you want to either retrieve it or create the one and only object. And hence the method must be static.

And, by the way, the instanceFlag is superfluous. You could equally well test the single pointer on being not equal to NULL.
 
Share this answer
 
v2
Comments
[no name] 18-Oct-13 9:22am    
If you use only the single pointer what happens when you destroy the object and try to set the pointer to NULL in the destructor?
nv3 18-Oct-13 9:42am    
What should happen? You set the pointer to NULL. The next call to getInstance() will create a new object, which is normally what you want.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900