Can static function access non static variables in C++?

(Last Updated On: March 17, 2018)

No, Static function of a class in C++ cannot access non-static variables, but, it can access static variable only. However, non-static member function can access static and non-static variable both.

Static function is not associated with class object, means without object using class name only it can be called. whereas non-static variables are associated with objects. Every object has its own copy of non-static variable. Since, static function does not know about object, so, it is impossible for a static function to know on which class object or class instance it is being called.

Hence, whenever, we try to call non-static variable from a static function, the compiler flashes an error.

Let’s check static and non-static variable accessibility from a static function with a simple C++ program example.

Example – Static function can access only static variable

In below example, we have a static variable b of int type and have initialize to 50, but inside static function the value of static variable b has been modified to 10. Hence, program will work correctly.

 

OUTPUT:
10

Example – Static function cannot access non-static variables
 

In above source code, compiler will flash an error i.e. illegal reference to non-static member A::a

Hence, accessing non-static members from static method in C++ programming is not possible.