-1

I'm trying to port this java singleton class to c++:

public class Singleton {
private static Singleton uniqueInstance;

private Singleton() {} 
public static Singleton getInstance() {
    if (uniqueInstance == null) {
        uniqueInstance = new Singleton();
    }
        return uniqueInstance;
    }
}

I ported to this C++ code:

class Singleton {
private:
  Singleton() {
    cout << "new Singleton is called" << endl;
  }
  static Singleton* uniqueInstance;
public:
   static Singleton* getInstance() {
    if (!uniqueInstance) {
      uniqueInstance = new Singleton();
    }
    return uniqueInstance;
  }
};

But I can't compile this! and gcc linker error occurred.

Milad Khajavi
  • 2,769
  • 9
  • 41
  • 66

2 Answers2

7

Make sure you define the static member outside the declaration:

Singleton* Singleton::uniqueInstance = nullptr;
Tushar
  • 8,019
  • 31
  • 38
2

Your cpp file probably does not reserve space for the static instance, you need to add Singelton* Singleton::uniqueInstance = NULL; to your cpp file and then allocate it in the first call

Alon
  • 1,776
  • 13
  • 31