0

I tried to make the following singleton class in C++

#pragma once
#include "stdafx.h"
#include <iostream>

class God
{
private:
    static God* firstObject;
    God()
    {
        if (firstObject != NULL)
            firstObject = this;
    }
public:
    static God* BuildGod()
    {
        if (firstObject != NULL)
            return firstObject;
        else {
            God();
            return firstObject;
        }
    }
};

and then use it like so

God* a = God::BuildGod();

Unfortunatley, it won't even compile and it returned the following errors:

LNK2001 unresolved external symbol "private: static class God * God::firstObject" (?firstObject@God@@0PAV1@A)

LNK1120 1 unresolved externals

ben
  • 15
  • 3
  • See http://stackoverflow.com/questions/449436/singleton-instance-declared-as-static-variable-of-getinstance-method if you are interested in making it thread safe in C++11. – BGR Jan 23 '16 at 22:09

2 Answers2

1

A static member of a class has to be defined outside the class, like

class God
{
...
};

God* God::firstObj;

Just beware that having the definition in a header file and including it mamy times calls for trouble.

  • holy shit man, that worked fine! thanks EDIT: just tried to add cast operator just in case as shown: `operator const char*() { return "sup"; }` it gives me the same error again – ben Jan 23 '16 at 22:00
  • Don't get what your code looks like now, this works https://ideone.com/nOIINQ – Bartosz Bosowiec Jan 23 '16 at 22:25
1

You actually have a worse problem than the build error, because you create a temporary object, and save a pointer to it to be used.

The statement

God();

creates a temporary object, and in the constructor you save a pointer to this temporary object in firstObject which you then return. Using that pointer will then lead to undefined behavior.

One of the usual ways of creating a singleton in C++ would be something like this:

class God
{
public:
    static God& get_instance() {
    {
        static God instance;  // This is THE instance
        return instance;
    }

private:
    God() {}
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621