Search code examples
c++thisname-hiding

Access member field with same name as local variable (or argument)


Consider following code snippet:

struct S
{
   S( const int a ) 
   { 
      this->a = a; // option 1
      S::a = a; // option 2
   }
   int a;
};

Is option 1 is equivalent to option 2? Are there cases when one form is better than another? Which clause of standard describes these options?


Solution

  • option 1 is equivalent to option 2, but option 1 will not work for a static data member

    EDITED: static data members can be accessed with this pointer. But this->member will not work in static function. but option 2 will work in static function with static member

    Eg:

    struct S
    {
       static void initialize(int a)
       {
          //this->a=a; compilation error
          S::a=a; 
       }
       static int a;
    };
    int S::a=0;