README:
PS: I've done my best to explain in the best simple way the argument, I've seen many of the other topics here about it, but in my opinion any of them explains the point properly
I know this argument has been passed many, many, many, many [for i<9000 print: many] times, but this time I (think) already got the point, so what I want to do is to expose my conclusions and be corrected if I'm wrong. If you want, you may mark this question for future readers, maybe in a sort of beginners section, I'll try to be brief.
Pointers and References almost do the same things, BUT, they are
basically (physically) DIFFERENT.
POINTER:
Pointers ARE VARIABLES, with their OWN address, which can hold their OWN value.
Look at this snippet:
int nInt=99; //address of variable nInt 000D893F
int* pPointer; //address of variable pointer 000C751C
pPointer= &nInt; /*
* address of &pPointer: 000C751C &just returns the address of
* value of pPointer: 000D893F
* value pointed by *pPointer: 99
*/
REFERENCE:
References ARE NOT variables, they are just ALIASES to ALREADY EXISTING variables
More clearly: when you delcare a variable (es. int nX=5
) you allocate some memory (4bytes) somewhere in the stack, assume its address is 000C763C
.
Imagine now this variable like a box with its value inside (5
), the box is named for your CPU 000C763C
but in your program is called nX
.
When you do something like:
int &nAlias = nX
you are saying to your compiler: hey look at this variable (address of nX
), its name is not only nX
but nAlias
too, these names ARE exactly the same memory cell, same memory address, same variable, so it means it must already be created (before creating a reference!), this means that nAlias
has not its own address nor can contain its own value, it's just another name of the same memory cell!
So imagine now our box called 000C763C
(nX
) by your CPU, with inside the value 5
and known by your compiler with names either nX
or nAlias
, exactly the same memory cell!
So I guess that it is only used by compiler pourposes. (I'm only guessing, I hope in a reply)
If I am right, I hope many people asking for it here will get a more clearer understanding about what these things really are, the rest of your knowledge would be easier...
Finally a personal opinion, I don't know why almost all the books or tutorials I've read, before explaining these arguments doesn't explain in this simple way what pointers and references are, I see people getting mad trying to understand so simple but tricky notions...
I hope I did a good deed!