I’m confused between the two. Thanks for any help !
Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain.
Despite above similarities, there are following differences between references and pointers.
References are less powerful than pointers
- Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
- References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
- A reference must be initialized when declared. There is no such restriction with pointers
Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have above restrictions, and can be used to implement all data structures. References being more powerful in Java, is the main reason Java doesn’t need pointers.
References are safer and easier to use:
- Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise )
- Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members.
In C++ Every memory block carries a unique address, which helps the compiler to access it for whatever task the program tells it. Pointers are the variables that store the address of these variables and logically point them.
Data type variable; Data type *pointer_variable= &variable; // Declaration with Initialisation Data type variable; Data type *pointer_variable; // Declaration pointer_variable= &variable; // Initialisation
A reference creates a variable that acts as an alias for our variable. This means that we can then access our variable either by its original name or by the name which the reference variable offers to us.
Data type variable; Data type &reference_variable=variable; // ‘&’ reference operator
Pointers Variables vs Reference Variables
A Pointer can work without initialising whereas a Reference cannot.
A Pointer can point to more than one variable of the same data type, whereas a reference can point to only one variable.
A Pointer can be initialised with NULL, whereas We cannot initialise a Reference with NULL.
Use references when you can, and pointers when you have to.
Refer to this resource for detailed Information