2

I have a class with a static function getSharedInstance, thus should give me a pointer to an already instanced version of the class.

Header:

class foo {
public:
  static foo *getSharedInstance();

private:
  static foo *sharedInstance;
}

Implementation:

foo *foo::getSharedInstance() {
    if(sharedInstance == NULL)
        sharedInstance = new foo();
    return sharedInstance;
}

The point I don't understand is, why do I get undefined reference to the variable sharedInstance?

1 Answers1

6

You have to instanciate it somewhere (generally in you class' cpp file):

foo *foo::sharedInstance;

The compiler assumes it will find the symbol (ie the pointer representing your instance) somewhere. However, if you don't define it, it wont find it and will therefor raise undefined reference

Xaqq
  • 4,308
  • 2
  • 25
  • 38