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:
Share on facebook
Share on twitter
Share on linkedin


The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may