#QuestionForBeginners
Why were references added to C++ when you could do everything that a reference could do using pointers?
I'd give the following 2 reasons:-
1. References can't be null (as also pointed by many others).
2. References , unlike pointers , can't be reseated, i.e., they can't be made to refer to an arbitrary memory location once they've been initialized. This is a huge benefit. Let me try to explain with an example:-
Suppose we have a pointer to an integer variable i, named p (int* p =&i), and we are incrementing the value of 'i' through 'p' via successive iterations of a loop. Now , if a programmer forgets to use to dereference operator before p (*p) while accessing the content of variable i, the memory address pointed to by p will simply keep on changing with each iteration, rather than the actual value of 'i'. This can be disastrous due to the potential threat of reading/ writing unrelated data.
There is no such danger with references as they are simply aliases to variables defined earlier . So, 'int& p= i; p++' is very much safe as it only modifies the value of i.
As for size considerations, I believe a reference takes the same amount of storage as occupied by a pointer (e.g. 64 bits on a 64-bit machine).
Please do let me know if I was right or wrong in my reasoning 😊