I am sorry if this question has been asked before (I tried to find it but in vain). I was going through Singleton design pattern at http://sourcemaking.com/design_patterns/singleton/cpp/1 (code is copied from there)
class GlobalClass
{
int m_value;
static GlobalClass *s_instance;
GlobalClass(int v = 0)
{
m_value = v;
}
public:
int get_value()
{
return m_value;
}
void set_value(int v)
{
m_value = v;
}
static GlobalClass *instance()
{
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
};
// Allocating and initializing GlobalClass's
// static data member. The pointer is being
// allocated - not the object inself.
GlobalClass *GlobalClass::s_instance = 0;
void foo(void)
{
GlobalClass::instance()->set_value(1);
cout << "foo: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
}
void bar(void)
{
GlobalClass::instance()->set_value(2);
cout << "bar: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
}
int main()
{
cout << "main: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
foo();
bar();
}
My question is in the lines if (!s_instance) s_instance = new GlobalClass;
s_instance = new GlobalClass will call the constructor but constructor is non-static and we are calling it from a static function. How does that work? Is Constructor "special" in this regard?
Thanks!