DIfference between Pointer Variable and Refrence
I want to ask that both Pointers and Reference in C++ can act as alias for the variable to which it points, and both contains the address of the variable to which they point : Then waht is difference between them
A reference just renames a memory location for the reader/programmer. Its more like renaming a constant with #define. The reference does not really 'contain' the address, instead the comiler *could* just substitute the address for the reference at the assembly code level.
A pointer is a variable (it 'must' have a memory location of its own (barring odd compiler tricks)) that *can* be used like a reference or it can point to nothing (NULL) (a reference cannot do that) and a pointer can get new memory from the os (new command) while a reference must 'point' to existing memory.
A pointer is a name for a memory location which holds the address of some object located somewhere else in memory. Among other things, a pointer is the only way you access a memory location which has been allocated in run time at your request from "heap space". You use a pointer as you would any other variable (almost - need to dereference, etc.).
A reference shares the address of the memory location of the argument/parameter being referenced. It exists only as a mechanism for passing or returning a parameter. You cannot otherwise use a "reference".
the main differences between ref's and pointers: syntax wise, references behave like objects, so if you have a reference to string called sref, you call sref.assign(), not sreef->assign()
Secondly, references are immutable, which means that they always point to the same object and you can't reassing them to a different object (as opposed to pointers). Consequently, a reference must be initialized in its definition, you can't create a non-initailzied reference. Finally, a reference must always refer to a valid object. There are no null references in C++.
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center