Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 920
αλεχολυτ Avatar asked Feb 14 '23 08:02

αλεχολυτ


1 Answers

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;
like image 175
Renjith Avatar answered Feb 16 '23 01:02

Renjith