Question

Hello World, I have been wondering why in c++ we use the this->ObjectName instead of this.ObjectName when referring to an object in c++. This is a simple syntax using the this->ObjectName :

     int x = 34;
     void take(int x) {
      this->x = x;
     }

But in other programming languages like java, we use :

     int x = 34;
     void take(int x) {
      this.x = x;
     }

So what am asking is why does the this statement in c++ differ from the this statement in java

Was it helpful?

Solution

This only applies to pointers. Expressions of class/struct type (references inclusive) use the more familiar dot notation:

class Whatever {
 public:
  int x;
  void take(int n);
};

class T {
  public:
   int x;
};

void Whatever::take(int n) {
  T t;
  T *pt = &t; // pointer
  T &tr = t;  // reference is basically just an alias

  pt->x   = n;
  (*pt).x = n; // can dereference a pointer, then use like a reference
  tr.x    = n;

  // Same for this.
  this->x   = n;
  (*this).x = n;
}

What may seem odd to you is that this is a pointer in C++ as opposed to a reference.

See also: Why 'this' is a pointer and not a reference? (Stroustrup introduces this before he created references in the language.)

OTHER TIPS

In Java/C#, almost everything is of reference type (except the primitive ones, struct in c# etc.). But in C++, both value and reference semantics are used. Use

Myclass{ 
 public: void foo(){} 
};

Myclass ob; //as value
ob.foo();

and

Myclass * ob; //as pointer
ob->foo(); 

Note: except pointer, there is another way for reference usage in C++, which is the reference itself, but in c++, reference is used as an alias for an object, so it is like the value type (like Java/C#).

 Myclass ob; //as value
 Myclass& ref=ob; // reference to ob
 ref.foo();

In C++ you have pointers. With pointers -> is used. With references/objects . is used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top