jeudi 23 juin 2016

why cannot static function reference static variable during singleton class creation in c++?

I was trying to understand singleton design pattern and created a simplest one:

#include <iostream>


class mySingleton{

private:
   static mySingleton *ptr;
   mySingleton(){ }    

public:
   static mySingleton* getInstance(){
     if(!ptr){
        ptr = new mySingleton();
        return ptr;
     } else return ptr;
   }

   void msg(){
     std::cout << " Hello World!! " << std::endl;
   }

};


int main(){

mySingleton* obj = mySingleton::getInstance();
mySingleton* obj2 = mySingleton::getInstance();

return 0;
}

When I try to compile I get :

Undefined symbols for architecture x86_64:
"mySingleton::ptr", referenced from:
    mySingleton::getInstance()       in ccm822LI.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

Why can't I use ptr inside a static function, since ptr is also a static variable? Am I missing something here?

Aucun commentaire:

Enregistrer un commentaire