If you have a variable and you want to pass-by-reference, making any changes to the original variable effect the originally allocated value.
You use a pointer for instance if you want to dereference a physical memory address as part of an array of allocated memory addresses.
// reference example
int value = 0;
int value1 = &value;
value1 = 2;
// value should equal 2
// pointer example
int value[5] = {1,2,3,4,5};
*value += 1;value++;
*value += 1;value++;
*value += 1;value++;
*value += 1;value++;
*value += 1;
// should now be {2,3,4,5,6} // reference example
int value = 0;
int& value1 = value;
value1 = 2;
// value should equal 2Both give you the guarantee that it's not pointing at the NULL address. In the case of const pointers, that's because you can't reassign it, and you'd never deliberately assign a const pointer to NULL. In the case of references, it's because there's actually no such thing as a null reference in C++.
That's not the case in Java and C#, which allow "null" to be a right-hand value for all types.
Uhh no. Neither the const pointer nor the reference can be reassigned. And you have it the wrong way around. References cannot be null, pointers can.
The other difference is that if you try and dynamic_cast a reference and it failed, it throws an exception where as a pointer just returns nullptr.
>That's not the case in Java and C#, which allow "null" to be a right-hand value for all types.
That's also wrong, primitives are not nullable.
I was wrong on reinitializing references as well. Thanks for pointing that out. As far as const pointers, I meant that they were unlikely to be null, since they would have to be initialized to null. Of course, then I realized that you could easily assign them to another null pointer that you didn't realize was null.
Not a good day for me, but I don't think it warrants that kind of snarkiness.
To my credit, please reread the part where I said "there is actually no such thing as a null reference."
I truly believe he knows his stuff, but even he made a mistake. He, however, didn't have to come up with his answer while people are staring at him.
myref = otherref + 10
is equivalent to
* myptr = * otherptr + 10
Now, most languages also have a notion of values that are neither pointers nor references, and primitives generally are expressed as values, but hopefully you get the point.