Search code examples
c++classstatic-methodsclass-members

How can i modify variables in static member function?


I have a code below, i want to modify class's variables in static function but there is some error. How can i fix it with "this" pointer?

There is no access to "this" pointer for static members in class,on the other hand I am trying to make an access to class variables in Static member function, therefore i am looking for a way to use "this" pointer of class "me" to do it.

class me {
  public:
     void X() { x = 1;}
     void Y() { y = 2;}

static void Z() {
  x = 5 ; y = 10;
}

public:
  int x, y;
};

int main() {
  me M;

  M.X();
  M.Y();
  M.Z();

  return 0;
}

I got this error :

invalid use of member ‘me::x’ in static member function.


Solution

  • You can pass a pointer to an instance to the method:

    class me {
    public:
        void X() { x = 1;}
        void Y() { y = 2;}
    
        static void Z(me* this_) { // fake "this" pointer
          this_->x = 5 ;
          this_->y = 10;
        }
    
    public:
        int x, y;
    };
    
    
    int main() {
        me M;
    
        M.X();
        M.Y();
        M.Z(&M);  // this works, but
        // usually you call static methods like this
        // me::Z(&M);
    
        return 0;
    }