Regardless of provided convenience of references over pointers such as needleless of dereferencing and rules specific to use of each ,
is there any logical reason to provide two language constructs as pointers and references or is it just a syntactic sugar?
(I guess the ultimate underlying implementation that compiler would use the same steps for references as do for pointers with implying/checking for rules defined for references by a language.)
NOTE : the question is not about rules have defined by languages on references such as "references are not allowed to assign NULL in C++ but pointers" etc.
You are asking two questions, if I understand correctly
- What is the difference between pointers and references
- Why support both data types
Here goes:
- A pointer refers to a location in memory where a datatype resides. The size of a pointer is fixed, given the underlying hardware, generally 4 or 8 bytes - totally regardless of what it is in fact pointing to. Furthermore, a pointer can be passed to a function using an invalid value -
foo(reintepret_cast<int *>(0xDEADBEEF) );
. In contrast, a reference ensures that the underlying data is valid - since the reference is an alias the the object itself and can't be moved from being so (providing the the referenced object is still in scope - edited per remark below). - There are reasons to support both types. The first reason is to ensure that data that is passed to functions is valid - without wasting cycles on testing pointer validity (not
NULL
). The second reason is that one can be sure that not only is the data pointing to a valid location, it is also pointing at a valid data object. But the main reason is that a reference allows us to enjoy the benefit of calling a function without passing arguments by value, yet still maintaining a guarantee that the argument refers to a valid value.