Differences between C++ and Java with this-pointer

R

Rasti

Hello,



I am trying to translate a C++ script to Java. Are there any differences
between the C++ this-pointer and the Java this-pointer?



Thank you

Flo
 
V

Victor Bazarov

Rasti said:
I am trying to translate a C++ script to Java. Are there any differences
between the C++ this-pointer and the Java this-pointer?

In Java 'this' is NOT a pointer. There are no pointers in Java.

And, if you have questions on Java, try a Java newsgroup.

Victor
 
J

Joe Gottman

Victor Bazarov said:
In Java 'this' is NOT a pointer. There are no pointers in Java.

And, if you have questions on Java, try a Java newsgroup.

Personally, I think that a question about the similarities and
differences between C++ and Java is on-topic for either C++ or Java
newsgroups. To answer the OP's question, in C++ 'this' is a pointer and in
Java 'this' is a reference, because Java doesn't have pointers. However,
the C++ 'this' pointer is rather strange, because it cannot be reassigned
and cannot be null. It probably should have been a reference. As I
understand it, the main reason it wasn't is because it was invented before
references were.

Joe Gottman
 
L

lilburne

Joe said:
However,
the C++ 'this' pointer is rather strange, because it cannot be reassigned
and cannot be null.

void func(A& a);


A* aptr = 0;
func(*aptr);

I think you'll find that within func a's this pointer will
be null.
 
J

Joe Gottman

lilburne said:
void func(A& a);


A* aptr = 0;
func(*aptr);

I think you'll find that within func a's this pointer will
be null.

Derefencing a null pointer, as you do when you call func(*aptr) results
in undefined behavior. You might have a's this pointer null inside the
function call, or you might have a core dump before func is even called.

Joe Gottman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top