Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing static member variables

Tags:

c++

Can I access static member variables of a class using dot notation or should I stick in access operator which is double colon?

like image 450
domlao Avatar asked Aug 25 '09 01:08

domlao


People also ask

How static members can be accessed?

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.

Can static variables access directly?

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.

Can we access static data member in static method?

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.

Can I access static variable in another function?

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.


1 Answers

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;
}
like image 61
KV Prajapati Avatar answered Sep 21 '22 10:09

KV Prajapati