J. Homer
J. Homer

Reputation: 147

Singleton Class not working into multiple files

Say I have this code:

#include <iostream>
using namespace std;

class Something
{
    int field1;

    static Something *nill;
    static bool initialized;

    static void initialize() {
        if (initialized)
            return;
        initialized = true;
    }

public:
    static Something* Nill()
    {
        initialize();
        return nill;
    }

    static Something* Singleton(int field1)
    {
        initialize();
        Something *ret = new Something();
        ret->field1 = field1;

        return ret;
    }
}

Something* Something::nill = new Something();
bool Something::initialized = false;

int main(void)
{
    Something *smth = something->Nill();
    return 0;
}

Why isn't 'Something' a Singleton Class, and how could I make it one? Also how could I split this code into 2 files a .h and a .cpp? I had problems with that because I have some global variables here and I don't know how to use them in other files..

Upvotes: 1

Views: 584

Answers (1)

vamirio-chan
vamirio-chan

Reputation: 351

This is not a singleton class. Singleton class implies that in any given time you cannot have more than 1 instance of the class. In your example, you're not only creating a new instance but even return new class objects in its methods.

Make a default constructor protected (copy or move constructors too if you really want to be sure it's as singleton). Then use your static 'nill' as shown below:

class Something {
protected:
  Something() = default;
...

int main() {
  Something::nill->Nill();
...

P.s. Are you sure you need a singleton? Your methods say opposite.

Upvotes: 1

Related Questions