Differences Between Pointers and References
- Pointers can be null pointers, but references cannot be null references. This leads to the following distinction.
- Pointers can be invalid, while references are always valid. If a pointer is a null pointer, it cannot be legally used. This requires checking the validity of a pointer each time it is used. In contrast, references don’t need to be checked.
- Pointers can be modified, references cannot. A pointer is a variable that stores an address pointing to an object, and it can be changed to point to other addresses, no longer pointing to the original object. However, a reference is bound to an object during initialization, and while you can modify the contents of the object, the reference cannot be reassigned to refer to another object.
- Based on the above situations, pointers and references have different applications. Pointers can be used in scenarios where you need to point to different objects at different times or where you might need to point to no object at all. If you always need to point to a single object and will not change what you’re pointing to after initialization, you should use a reference.