what is the difference btw a pointer and a reference in C++? int *ptr; int &ptr; correct me if i am wrong, both of them hold the address of an interger variable when assigned to them and they can be used as aliases . Are the just different implementations or is the a difference btween the two ? Thanks in advance
One difference I know is One is alias. i.e. you have 2 things exactly alike and the other is a pointer to the first object. Analogy can be x and y hold the same data. x holds the data and y knows its address where the data of x is
'Alias', as Shabbir says, is the perfect word. A reference is simply another name for an existing object. Consequently, you cannot write "int &ptr;" because you have not said what 'ptr' is another name for. You must write "int &newName = a;". A pointer, on the other hand, is like a name in your address book; it contains information about where something lives. It is not the something, just information about its location.
But internally even for a reference to work all it does is stores the address of the location it references .Thats how both the variable and the reference access the same copy of the variable and do not have different copies. Consequently even a pointer does the same but we manually assign it the address of the location to reference unlike in references. Am i right ? or is there any other implementation for reference ?
No, the reference does not store the address of the variable for which it is another name. The equivalency is a compiler issue. You cannot have an unitialized reference. When a reference is passed to a function, the value passed is the same value that would be passed if the original were used. This is, of course, at this point, an address, but there is one less level of indirection than there would be if a pointer were passed. You might want to write some code using a pointer and a reference and examine the assembly-language code that is emitted by the compiler.