Can I access static member variables of a class using dot notation or should I stick in access operator which is double colon?
A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class.
Static variables in Java belong to the class i.e it is initialized only once at the start of the execution. By using static variables a single copy is shared among all the instances of the class, and they can be accessed directly by class name and don't require any instance.
In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
Static variables in methods i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated.
If you have an instance variable you may use dot operator to access static members if accessible.
#include <iostream>
using namespace std;
class Test{
public:
static int no;
};
int Test::no;
int main(){
cout << "\n" << Test::no;
Test::no=100;
Test a;
cout << "\n" << a.no;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With