Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Singleton in different classes

Tags:

c++

singleton

How do you create a instance of a singleton that can be used in other classes?

For Example:

//Singleton_Class.h

#ifndef Singleton_Class
#define Singleton_Class

class Singleton
{
private: 
  static Singleton _instance;

  Singleton() {}
  ~Singleton() {} 
  Singleton(const Singleton &);
  Singleton & operator=(const Singleton &);

public:
 static Singleton &getInstance(){return _instance;}
};

Singleton Singleton::_instance;

#endif


//Main.cpp

#include "Singleton_Class.h"

int main()
{
    Singleton &s = Singleton::getInstance();  //Use the instance
}

//ClassA.cpp

#include "Singleton_Class.h"

class A
{
public:
 A(){};
};

I get a linking error when trying to include the single class header for class A (LNK2005): "private: static class Singleton Singleton::_instance" (?_instance@Singleton@@0V1@A) already defined in Singleton Class.obj

like image 538
cpx Avatar asked Jul 02 '26 06:07

cpx


1 Answers

You need to define the instance variable in one of your source (.cpp) files, not in the header file.

If the instance variable is defined in the header file, then when that header file is included in multiple source files, it ends up getting defined multiple times (which is what the error says).

like image 102
James McNellis Avatar answered Jul 03 '26 19:07

James McNellis