-1

I have the following piece of code .

class base {

private:
    static base *b_h;
public:
    static base* getInstance() {
        if(!b_h) {
            b_h = new base();
        }
        return b_h;
    }
};
    
int main()
{
    base* b;
    b = base::getInstance();

    return 0;
 }

When i try to compile, I am facing the below error :

main.cpp:(.text._ZN4base11getInstanceEv[_ZN4base11getInstanceEv]+0x15): undefined reference to base::b_h' /usr/bin/ld: main.cpp:(.text._ZN4base11getInstanceEv[_ZN4base11getInstanceEv]+0x1c): undefined reference to base::b_h'

Can someone please help me on this ?

Somesh
  • 82
  • 8

1 Answers1

2

You need to define the static member outside the class and in exactly one compilation unit (.cpp file).

base* base::b_h = nullptr;

Alternatively make it a static variable inside the getInstance() function:

class base {
  public:
    static base* getInstance() {
      static base *b_h = new base();
      return b_h;
    }
};

b_h will be initialised the first time getInstance is called.


But in general try to void the singleton pattern if possible.

bitmask
  • 32,434
  • 14
  • 99
  • 159