Question

although there are a lot of answers to this topic, I still have a problem.

I want, like everybody, to implement a Singleton pattern. I tried with this:

class Factory
{

private:
    Factory(void);
    static Factory* self_inst;

public:

    ~Factory(void);

    IPortIO* getStrategy(int portType);
    static Factory *getInstance()
    {           
        if(self_inst == NULL)
            self_inst = new Factory();
        return self_inst;       
    }

};

The problem comes when I call *self_inst* in the getInstance() static Method. A lot of people said that when using static variables, you must not only declare it, but define it somewhere else. Well, I've problem trying to define it in very place:

1 Outside the class:

Factory* Factory::self_inst;

2 Outside the class, with a value:

Factory* Factory::self_inst=NULL;

3 Inside the static method:

static Factory *getInstance()
{     
    Factory* Factory::self_inst;      
    if(self_inst == NULL)
        self_inst = new Factory();
    return self_inst;       
}

4 and inside the static method but with a value:

static Factory *getInstance()
{     
    Factory* Factory::self_inst=NULL;      
    if(self_inst == NULL)
        self_inst = new Factory();
    return self_inst;       
}

Nothing works! Finally I decided not to create a static attribute in the class, but a static variable inside the static method. This works, but it definitely not the same and also not a good programming practice, since what should I do if I need to access the same variable with two statics methods? It's not my case, but it's a good question and I would really like to know if someone knows hot to do it.

Was it helpful?

Solution

Number 2 is right (actually so is number 1, because the default initialisation is to NULL), just remember to put it in a cpp file, not in the header.

If it's still not working post the error message.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top