Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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 
}
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


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

 

 

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