C ++: static member variable

Statement: "Static member variables can ONLY be modified by static methods."

Is this statement correct or can static member variables be changed by non-static methods?

Thank!

+3


source to share


4 answers


This is not true. A static member can be accessed and modified using a non-static member function.



+7


source


It is not right. Data items static

can be modified by any member function. static

methods can also be called by any member function.

Quite the opposite: methods static

cannot call methods static

and cannot access <elements static

.



This is because members static

(methods and data) are bound to the class, whereas non-static is bound to instances of the class.

+7


source


The statement is incorrect. You can modify static members from any member function of the class and from any other function from which the static member is visible (i.e. public statics can be modified from anywhere).

+1


source


static

Data members (and static member functions) can be accessed from anywhere in the program if this access specifier allows:

struct test {
   void foo() {
      x = 1;
      bar();
   }
   static bar() {
      x = 2;
   }
   static int x;
};
int test::x = 0;
int main() {
   test::bar();
   test::x = 3;
}

      

0


source







All Articles