Part 1 - pointer vs reference

> What's a pointer?

Well, it's an address of memory that contains object of pointer's type. That's a very condensed definition, but let me explain.

As you can see image is split into 2 parts: variables (on the left) and memory layout (on the right).

First of all, we have int a with value of 1234. If you think about it, it has to be stored somewhere in computer's memory. On image it's stored in cell with address of 0x14.

For now, let's skip int& b and dive into int* c. It's a simple pointer. What that means, is that your variable b contains address of memory. In this case it's 0x14. You can dereference it (which means to actually lookup said memory address) and get the same value as in variable a (which is 1234).

Lastly, we have int** d. This means we have a pointer to a pointer. In this example, we have address 0x16, under which we have a pointer to address 0x14, under which there is a value of 1234.

So, we have 3 varaiables, a, c and d, which all point to same value. The thing is, pointers are "optional". That means they can also have value of nullptr (for the sake of this example let's say that nullptr = 0). When a pointer is equal to nullptr, think of it as "there may have been somewhere at this address, but is either no longer there or isn't there yet".

You might ask yourself:

> Why even have something that can be non-existent"?

Well, the answer is a bit complex, so the long story short is: when you use pointers, you need to "request memory". Said memory has to be "returned" as well. Problem is that both of those operations occur during runtime (instead of compile time). When you "return" your memory you still have a variable in your code that you could reference - that pointer would be a nullptr. Same for if you tried to access a variable that you haven't "requested" memory for.

int* a;
// "a" here is "nullptr", so any attempt to use it would end in dereferencing a "nullptr"
a = new int;
// here "a" is a valid
delete a;
// and again, "a" became a "nullptr", can't use

Side note: this code is horrible and serves educational purposes only. Whole point of this series is to not write code like this.

Knowing what a "pointer" is, we can answer a question:

> What's a reference?

Well, reference is a non-nullable pointer. You might ask yourself:

> Well, wasn't the whole point of pointers that they are nullable?

and I would answer yes, yes it was.

You are only allowed to have a reference only if compiler knows, that value is non-nullable. Example? Let's go back to that image. If we want to get an address of a, then that means it IS somewhere in memory (or the program would have crashed before). Based on the fact that we did not crash we can deduce, that address of a exists and it won't be nullptr. And that's exactly what b is.

Mastodon