I saw the following code:
http://sourcemaking.com/design_patterns/singleton/cpp/1
class GlobalClass
{
private:
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;
}
};
GlobalClass *GlobalClass::s_instance = 0;
void foo(void)
{
GlobalClass::instance()->set_value(1); // static variable calls non-static functions
cout << "foo: global_ptr is " << GlobalClass::instance()->get_value() << '\n';
}
As I know (please correct me if I am wrong here),
-
Static functions can only access(write/read) static member variables
-
Non-Static functions can access(write/read) static member variables
Based on above sample, it seems that a static variable can access non-static functions.
Is this correct?
Variables don’t call anything
(This doesn’t really address the sample code, but it corrects a misconception in the two “rules” listed beneath the code)
A static member function is a member, and can access all public, protected, and private members of its class, both static and instance.
However, static member functions have no
thispointer, so to access an instance member, the instance needs to be specified.