Intro to C++ Pointers
Pointers are a great tool to make your applications faster and more powerful, what they are is essentially references to a certain memory location.
For example if I have something like:
1
|
int foo = 27;
|
Let’s say that the memory address of my
1
|
foo
|
variable is 1672. You’ll be able to access this using the
1
|
&
|
(address-of) operator and create a pointer for that address using
1
|
*
|
(dereference operator).
So let’s create a pointer that points to foo:
1
|
int* bar = &foo;
|
Great! Now we have a pointer to foo, with it we can access and modify foo’s data with the dereference operator like so:
1
2
3
4
|
int baz = *foo;
cout << baz;
*foo = 30;
cout << baz;
|
This would result in:
1
2
|
27
30
|
Of course since we’re only using integers this doesn’t seem like that much help, but if you’re writing a bigger application and have big classes with lots of methods and variables it will come in very handy with the arrow operator
1
|
->
|
to access those members very simply with your pointers.
For example:
1
|
Person* Peter = &GetPlanet()->GetContinent()->GetCountry()->GetCity()->GetPeter();
|
So instead of having to write
1
2
3
|
int height = &GetPlanet()->GetContinent()->GetCountry()->GetCity()->GetPeter().Height;
int weight = &GetPlanet()->GetContinent()->GetCountry()->GetCity()->GetPeter().Weight;
int age = &GetPlanet()->GetContinent()->GetCountry()->GetCity()->GetPeter().Age;
|
You can just do
1
2
3
|
int height = Peter->Height;
int weight = Peter->Weight;
int age = Peter->Age;
|
Much easier, right? Not only you’re saving a lot of code, you’re also saving memory, thus making your program run (sometimes much) faster. If you’re pointing to an object with huge amounts of data making a copy of this object would mean wasting a lot of resources and time, but if instead you just point to it you can imagine how much more efficient that can be.
These are only a few of the many advantages of using pointers, so I encourage you to go and try them out for yourself and make some cool stuff with them.