It's oh last time we talked about pointers and in this lecture I want to talk about a concept that's
very similar which is references.
So a reference it is a variable that also has an address as its value.
So there are some key differences between pointer and a reference.
But first let's look at how to make one.
So we had X was 5 in a reference and that uses the ampersand instead of the star we have four in set
to X like this.
OK so don't get this ampersand can use with address when it's in a declaration for a variable this means
reference
so.
Notice also that we set the reference and we're not taking the address of X.
OK so before we had we had the address of X for pointers but we don't need to do that it possible sort
of do that for us with references.
K so there is also something else to note.
And that's not really immediately obvious.
And that is you can't use something like this.
So we had another reference in reference to.
You can't do this in you'll see if you try to do this.
OK so says the declaration a reference variable and ref 2 requires initializer.
And so it needs to have an initial value at the start k and that is because a reference is really an
alias.
It needs something to reference as it were right.
Otherwise it it doesn't make any sense.
OK so you can't have a reference that doesn't reference anything that doesn't it doesn't work.
So this is actually pretty similar to constants if you're a member or so constant in.
You know Max you couldn't have a concept like this for example
in this.
Right.
So default initialization of object of conc type constant.
Right.
So this is very similar.
So and this should make sense because you can't change Max later because it's a constant.
So it's the same thing for references.
So another key difference is between between the references and pointers is that you don't need to dereference
a reference in order to change the value pointed to by the reference.
So we had this if you want to change it to say giraffe to 10.
And if you want to see out the value x is
x and it's
X is 10 right.
So the reference actually changed x.
So we noticed you didn't use the dereference operator star operator.
You remember from last time.
That's because again C++ sort of does that for you already.
So there's no need to use it in order to change the value.
So I really think of references as the original variable self.
So that's really my mental model for them.
I can do it any operation that I can do with the original.
So might be asking then when should I use a reference over a pointer and just use a pointer when you
want it to point to either nothing.
I remember that null pointer or a real value and you should use reference when you don't always want
to point to a real value.
OK so there's this subtle but it's it's very important.
So this will become much more clear as we start using them.