1

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.

Tim
  • 11
  • 2
  • Generally recommended approach to Singleton: https://stackoverflow.com/a/1008289/3807729 – Galik May 31 '18 at 03:53

2 Answers2

1

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.

Sid S
  • 6,037
  • 2
  • 18
  • 24
  • Perfect... thank you. It would not let me define the static member in the header. I tried both methods as you wrote and they both worked. I ended up using the latter, much cleaner. – Tim May 31 '18 at 17:18
0

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

Singleton* Singleton::instance = nullptr;
code707
  • 1,663
  • 1
  • 8
  • 20