Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between const. pointer and reference?

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

like image 618
Arnkrishn Avatar asked Feb 25 '10 17:02

Arnkrishn


People also ask

What is difference between pointer and reference?

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.

What is a const pointer?

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.

Can const pointers be null?

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 .

What is the difference between pointer and reference in Java?

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.


1 Answers

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.

like image 194
Brian R. Bondy Avatar answered Oct 30 '22 03:10

Brian R. Bondy