#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *getInstance();
private:
Singleton(){}
static Singleton* instance;
};
Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance()
{
if(!instance) {
instance = new Singleton();
cout << "getInstance(): First instance\n";
return instance;
}
else {
cout << "getInstance(): previous instance\n";
return instance;
}
}
int main()
{
Singleton *s1 = Singleton::getInstance();
Singleton *s2 = Singleton::getInstance();
return 0;
}
i didn't understand why should singleton instance variable should be initilized with 0 in the following line. Singleton* Singleton::instance = 0; Because when i forgot to initilize the instance i got error as
singleton.cpp:(.text+0xc): undefined reference to `Singleton::instance'
singleton.cpp:(.text+0x2d): undefined reference to `Singleton::instance'
singleton.cpp:(.text+0x43): undefined reference to `Singleton::instance'
singleton.cpp:(.text+0x5b): undefined reference to `Singleton::instance'
collect2: error: ld returned 1 exit status