Difference between "this" in C++ and "this" in Java

We usually use this like a pointer (in fact , it is a pointer) in C++
Here is the code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std ;

class Test{
    private :
    int a ;

    public :
    void setA(int b){
        this->a = b ;
        cout << getA();
    }

    int getA(){
        return this->a ;
    }
};

int main(){
    Test obj1;
    obj1.setA(20);
    return 0 ;
}


In java , we use "this" like this.
1
2
3
4
5
6
public class Test {
  private int a ;
  public setA(int a){
   this.a = a ;
  }
}

We don't have pointers in Java. Still , Can anyone please explain the difference ? thanks
In Java, this is a reference (Java references are similar to C++ pointers).
Last edited on
closed account (o3hC5Di1)
Hi there,

I'm no expert in C++ and I dont' know any java, but this is what I gather:

Pointers in C++ are variables - this means they hold a value in memory.
The value of a pointer is the address of another variable.
So in C++, this is a variable, of which the value is the address of the current object.

In Java (according to what I just found off of google) this is a reference.
A reference is an alias, a different name, for the current object, but it doesn't occupy any space in memory (for as far as I can tell).

All I know is that pointers, being variables, provide you with more flexibility in the way you handle them. Possibly in this case the actual usage difference is minor.
Hopefully one of the experts around here can shed a bit more in-depth light on this.

All the best,
NwN
NwN wrote:
In Java (according to what I just found off of google) this is a reference. A reference is an alias, a different name, for the current object, but it doesn't occupy any space in memory

That's a little backwards: a reference is an alias/different name in C++, but not in Java, where "reference" is how they call a pointer. (the difference is when you assign to a reference in C++, you're modifying an object, but when you assign to a pointer in C++ or "reference" in Java, you're not modifying an object, you're only changing what the pointer/java reference points to)

As for OP: in C++, we normally write "a = b;" and "return a;". The this pointer is rarely needed. (and the reason it's a pointer and not a C++ reference is purely historical: it was invented before references were invented. Had it been designed today, it would have had a reference type)
Last edited on
thanks guys .
Topic archived. No new replies allowed.