Tim
Tim

Reputation: 11

Trouble accessing a Singleton Class C++

I am trying to write a singleton class for a centralized access point for game data from various classes. Here is what I have... just generic for now.

--> Singleton.h

#pragma once

class Singleton {
public:
    static Singleton* instance;
    static Singleton* Get();

private:
    Singleton() {};
};

 Singleton* Singleton::Get() {
    instance = new Singleton();
    return instance;
}

--> and in the main.cpp I attempt to call into existence the Singleton class

#include "Singleton.h"
Singleton* single = Singleton::Get(); 

--> and I get the following errors in MS Visual Studio

LNK2001 unresolved external symbol "public: static class Singleton * Singleton::instance" (?instance@Singleton@@2PAV1@A) TimePilot84 E:\VC\TimePilot84\TimePilot84\main.obj 1

I do not understand how to instantiate this class if its constructor is private and if accessing the public constructor is public yet yields an err

I realize that I am not testing to see if the class exists before calling the constructor in the Get function and that I have no destructors as of yet.

I only make one single call to this function in main, and it will not compile. Thanks for your help.

Upvotes: 1

Views: 235

Answers (2)

code707
code707

Reputation: 1701

You need to define static variable instance. Add following after declaration of class:

Singleton* Singleton::instance = nullptr;

Upvotes: 0

Sid S
Sid S

Reputation: 6125

You have to define the static member. This should be done in a .cpp file rather than in the header :

Singleton *Singleton::instance = nullptr;

Also note that the instance should only be created once, so Get() should look like this :

Singleton *Singleton::Get()
{
    if (!instance)
    {
        instance = new Singleton;
    }
    return instance;
}

Alternatively, you could ditch the static member variable and implement Get() like this:

Singleton *Singleton::Get()
{
    static Singleton instance;
    return &instance;
}

The latter has the bonus effect of calling Singleton::~Singleton() when your program exits.

Upvotes: 1

Related Questions