What is the difference between a constant pointer and a reference?
Constant pointer as the name implies can not be bound again. Same is the case with the reference.
I wonder in what sort of scenarios would one be preferred over the other. How different is their C++ standard and their implementations?
cheers
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
A constant pointer is one that cannot change the address it contains. In other words, we can say that once a constant pointer points to a variable, it cannot point to any other variable. Note: However, these pointers can change the value of the variable they point to but cannot change the address they are holding.
The null pointer constant is guaranteed not to point to any real object. You can assign it to any pointer variable since it has type void * . The preferred way to write a null pointer constant is with NULL .
Reference: A reference is a variable that refers to something else and can be used as an alias for that something else. Pointer: A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at that address.
There are 3 types of const pointers:
//Data that p points to cannot be changed from p const char* p = szBuffer; //p cannot point to something different. char* const p = szBuffer; //Both of the above restrictions apply on p const char* const p = szBuffer;
Method #2 above is most similar to a reference.
There are key differences between references and all of the 3 types of const pointers above:
Const pointers can be NULL.
A reference does not have its own address whereas a pointer does.
The address of a reference is the actual object's address.
A pointer has its own address and it holds as its value the address of the value it points to.
See my answer here for much more differences between references and pointers.
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