4

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?

αλεχολυτ
  • 4,792
  • 1
  • 35
  • 71

3 Answers3

5

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;
Renjith
  • 397
  • 5
  • 14
2

Have you tried this option?

struct S
{
   S(int a) : a(a) { }
   int a;
};

Have a look at the following:

12.6.2 Initializing bases and members

[12] Names in the expression-list or braced-init-list of a mem-initializer are evaluated in the scope of the constructor for which the mem-initializer is specified. [ Example:

class X {
   int a;
   int b;
   int i;
   int j;
public:
   const int& r;
   X(int i): r(a), b(i), i(i), j(this->i) { }
};

initializes X::r to refer to X::a, initializes X::b with the value of the constructor parameter i, initializes X::i with the value of the constructor parameter i, and initializes X::j with the value of X::i; this takes place each time an object of class X is created. — end example ] [ Note: Because the mem-initializer are evaluated in the scope of the constructor, the this pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized. — end note ]

Community
  • 1
  • 1
iavr
  • 7,547
  • 1
  • 18
  • 53
1

Both forms are identical unless a is a virtual function. I'd prefer this->a, because it does what I usually want even if a is a virtual function. (But isn't it better to avoid the name clash to begin with.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329