char *str = "Hello"; char *ptr = str; char *&rptr = str;
What is the difference between ptr and rptr? I understand rptr is a reference to a pointer(in theory) but how does it differ in terms of implementation with ptr?
Are references in C++ implemented using pointers?
A reference to a pointer is a modifiable value that's used like a normal pointer.
Note: It is allowed to use “pointer to pointer” in both C and C++, but we can use “Reference to pointer” only in C++. If a pointer is passed to a function as a parameter and tried to be modified then the changes made to the pointer does not reflects back outside that function.
No, you can't make a pointer to a reference. If you use the address-of operator & on it you get the address of the object you're referencing, not the reference itself.
A pointer to reference is illegal in C++, because -unlike a pointer- a reference is just a concept that allows the programmer to make aliases of something else. A pointer is a place in memory that has the address of something else, but a reference is NOT.
str stores the address (and therefore points) to a literal string, "Hello", which is stored somewhere in a read-only segment of memory.
ptr points to the same address as 'str'.
rptr basically points to 'str' (not to the same pointee as str, but to str itself). It might be unusual to use 'points to' for references but they're really very much like pointers themselves (in this case a pointer to a pointer) except with slight syntactical differences and the restriction that they cannot point to any other address during their lifetime.
It would be analogous to:
char** const rptr = &str;
Like a reference, rptr above cannot be assigned a new address (it cannot change what it's pointing to), but it can be free to change its pointee (which happens to be a pointer in this case to 'str').
*rptr = 0; // after this, str == 0
References are pretty much the same as a read-only pointer (not a mutable pointer to read-only pointee) only they don't require a dereferencing operator to get at the pointee (the referenced data):
char *str = "Hello"; char *&rptr = str; rptr = 0; // after this, str == 0
The only difference from the above example with a read-only pointer to pointer is that we didn't have to use the operator*.
const references also have the unique property of being able to extend the lifetime of temporaries, but that's probably beyond the scope of the discussion.
What is the difference between ptr and rptr?
If you do char *world = "World"; rptr = world;
and then print str
, it will print "World". If you do ptr = world;
and then print str
, it will print "Hello".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With