#include<iostream>
usingnamespace std ;
class Test{
private :
int a ;
public :
void setA(int b){
this->a = b ;
cout << getA();
}
int getA(){
returnthis->a ;
}
};
int main(){
Test obj1;
obj1.setA(20);
return 0 ;
}
In java , we use "this" like this.
1 2 3 4 5 6
publicclass Test {
privateint a ;
public setA(int a){
this.a = a ;
}
}
We don't have pointers in Java. Still , Can anyone please explain the difference ? thanks
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.
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)