Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Jul 7, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
  static Singleton * instance();
  Singleton * p;
  static Lock lock;

Singleton * Singleton::instance()
 lock.get_lock(); // OK, lock is a static member
 if (p==0)
  p=new Singleton;
 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
  static void func(C & obj);
  int get_x() const;
 int x

void C::func( C & obj)
 int n = obj.get_x(); // access a member through reference 
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date