Hi,
what is the advantage of using reference over constant pointer?
Can they be used interchangeably?
Printable View
Hi,
what is the advantage of using reference over constant pointer?
Can they be used interchangeably?
The biggest difference is a pointer can be null
they're different types. and they're mostly interchangable at the code level.
the differences being:
pointers can point to "anywhere", including null (and it's easy to make a pointer point to anything you want).
pointers can be initialized and assigned
references "point to" objects. making a reference NOT "point to" an object typically involves a detour over a pointer which sidesteps the problem. So for the most part it is easier to make "clean" code with references.
references can only be initialized (i.e. you can't change a reference, you can only change what a reference "points to".).
pointers tend to confuse programmers, especially new programmers. It also opens the question as to "who owns the pointer, and do I need to dispose of the pointer when I'm done with it".
the rule of thumb should be:
Use references. Only use pointers when a reference won't work.
Thanks.
So is it wrong to say Reference is constant pointer?
Yes, that would be incorrect.
If you really have to... you could say that a reference "behaves like" a dereferenced const pointer to an object.
saying a reference IS a constant pointer is wrong because:
* they aren't equal, they're different types, so "IS" in that sentence is wrong. you access a member from a reference via the 'dot operator' or "object member selection operator" to use the proper term as in ref.member, where you access a member of a const pointer via the 'arrow operator' or "pointer member selection operator" as in ptr->member.
So you use them differently in code. If you change a function prototype from a reference to a const pointer you will also need to change all the indirections for the code to compile and work properly.
* so to extend the above, saying it's like a dereferenced const pointer (*ptr) you could use the in a similar manner as in (*ptr).member being equivalent to ref.member
* then there's still the matter that a const pointer still has ambiguity in who owns the pointer (do you need to delete the pointer ?) and that the pointer value may not point to an actual object. so you may need to test against NULL (and/or other specialty values).
also note that very few code gets written that has a const pointer (you do see '(variable) pointers to const something' a lot) and I'd even guess a lot of c++ programmers would be confused at the syntax thereof. Again, more reason to avoid pointers where possible and use references instead.