Difference between reference and const pointer
Can someone tell me the difference between reference and const pointer. Not in the way its used, but the way it is implemented.
My understanding
Reference - Always referes to the same location, but the content can be changed.
Const Pointer - Cannot change the location it points to, but can change the value.
Is that right?
So...
Thanks and Regards
Kannan S
Re: Difference between reference and const pointer
Quote:
Originally posted by mailtokannan
Can someone tell me the difference between reference and const pointer. Not in the way its used, but the way it is implemented.
My understanding
Reference - Always referes to the same location, but the content can be changed.
Const Pointer - Cannot change the location it points to, but can change the value.
Is that right?
So...
Thanks and Regards
Kannan S
It is irrelevant how references are implemented by a particular compiler. They is likely to be implemented as pointers (or addresses), on the machine code level. But the Standard doesn't specify this, AFAIK.
The difference between a reference and a pointer const is conceptually, at the level of the C++ programming language, despite they behaving very alike.
A reference is the object itself and cannot be resettled (made to referre to another object) no matter what. A pointer const is simply a pointer the compiler consideres to be const.
Thake this piece of code, for example:
Code:
int a = 10;
int &r = a;
int * const p = &a;
const_cast<int *>(p) = &a + 1;
First of all r and a are one and the same object. They refere to the same memory location, as opposed to p, which referes to a memory location that contains the address of a.
The last line of code shows that you actually can change the address p points to -- at least in a way the compiler will accept. Executing the last line of code has undefined results, because, depending on the context, the compiler may choose to place p in a read-only memory area. The example is purely academical, and is a no-no for the daily coding practice.