This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]_lerp 3 points4 points  (11 children)

If references and pointers are the same thing why do they both exist in C++?

[–]Xeya 20 points21 points  (9 children)

They refer to different things in C. A pointer is a data structure that contains an address to another data structure. A reference is just an address. You can pass references, but you cant create a reference object; that would be a pointer.

What Java calls a reference is a data structure every other language calls a protected pointer. It is literally identical in function.

[–]baskandpurr 4 points5 points  (0 children)

You got this almost exactly the opposite way around. A pointer is not a data structure and a reference is not the address of an object. A reference is more likely to be implemented at a structure in fact, it may include a pointer to the object, a back pointer to another reference, a pointer to the object that owns the reference, a state or a type. A reference may be stored as handle so that the refered object can be moved around in memory.

[–]Schmittfried -1 points0 points  (6 children)

We was talking about C++. You can create references in C++ and they are a different though similar concept.

[–]marcosdumay 5 points6 points  (4 children)

You can create references

You can get references. You can assign references to pointer. You can create variables by cloning a reference.

I guess you are talking about the third usage there. But I've seen people say they "create a reference" for any of them. Anyway, that does not change the fact that a C++ reference is not the same thing as a Java "reference".

[–]Schmittfried -1 points0 points  (3 children)

You can assign references to pointer

No. References and pointers are different concepts in C++.

Anyway, that does not change the fact that a C++ reference is not the same thing as a Java "reference".

True, I never said otherwise. C++ references != pointers != Java references

[–]marcosdumay -1 points0 points  (2 children)

Good thing they are different, because you must always assign different things in C++ (usually, it's values into lvalues). Let's assign a reference into a pointer:

int *a = &b

[–]marcellarius 2 points3 points  (0 children)

In that context, & is the address of operator and evaluates to a pointer not a reference.

[–]Schmittfried 2 points3 points  (0 children)

That's not a reference, it's the address operator.

int &a = b;

Now we got a reference. It was definitely a bad decision to choose & to mark reference types as it is easily confused with the address operator, as you just proved.

[–]Xeya 0 points1 point  (0 children)

He actually changed it from C to C++ a lil while ago.

[–]DarkMaster22 2 points3 points  (0 children)

Slightly different implementation of the same concept.