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.
class A{
static int b;
public:
//Static function
static int GetValue(){
b = 10;
return b;
}
};
//initialize static variable
int A::b =50;
int main(){
//Static functin call
cout<< A::GetValue();
return 0;
}
OUTPUT:
10
Example – Static function cannot access non-static variables
class A{
int a;//non static
public:
//Static function
static int GetValue(){
a = 10;
return a;
}
};
int main(){
cout<< A::GetValue();
return 0;
}
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.