Accessing Members of a Class in a Static Member Function

Accessing Members of a Class in a Static Member Function

A static member function doesn’t take an implicit this argument, as do ordinary class member functions. Therefore, it can’t access any other members of its class unless they are also static. Sometimes, you have no choice but to use a static member function, especially when you want to run it in a separate thread but you still need to access other members of the class from that function. There are two solutions: either declare these members static, so that the static member function can access them directly:

 class Singleton{ public:  static Singleton * instance();private:  Singleton * p;  static Lock lock;};Singleton * Singleton::instance(){ lock.get_lock(); // OK, lock is a static member if (p==0)  p=new Singleton; lock.unlock(); return p;}

Alternatively, pass a reference to the object in question as an argument of the static member function, so that it can access the object’s members through that reference:

 class C{public:  static void func(C & obj);  int get_x() const;private: int x};void C::func( C & obj){ int n = obj.get_x(); // access a member through reference }


Share the Post: