First look at pointers

On this round, we have studied something about references in Python and a bit more about references in C++. However, the most attentive students might have noticed that references do not work the same way in Python and C++.

In Python, assigning something to a reference will change the target of the reference:

person1 = Person("Kalle", 6)
person2 = Person("Ville", 5)
winner = person1
../../_images/python_olioviite_1_en.png

The reference winner now points to the same object as the reference person1. But after executing the following line of code

winner = person2

the reference winner points to the same object as the reference person2.

../../_images/python_olioviite_2_en.png

In C++, assigning something to a reference will change the value of the target:

int integer = 42;
int& integer_ref = integer;

integer_ref = 100;

After the assignments above, the value of the variable integer is 100, and the reference still points to the variable integer.

../../_images/viitekuva_en.png

The references of C++ are constant. Therefore, you cannot change a reference in C++ to point to a new object, but it will always point to the same place.

C++ also has another data type meant for indirect pointing: pointer. The pointers in C++ work in a very similar way to references in Python.

As well as C++ references, the pointers need you to define the type of variable they are going to be pointing to. In C++, while defining a variable you can make it a pointer by adding * between the name of the data type and that of the variable. You can initialize the pointer by referencing the variable that will be the pointer’s target. Therefore, &variable will create a pointer that points to the variable in question.

target_type* variable = &target_variable;

for example, with integers:

int integer = 42;
int* integer_ptr = &integer;
../../_images/osoitinkuva_en.png

So, a pointer is a variable that stores a reference. Because a pointer is a variable, you can also change the value it points to:

Person person1("Kalle", 6);
Person person2("Ville", 5);
Person* winner = &person1;
../../_images/cpp_olioviite_1_en.png

The pointer winner now points to the object person1. But after executing the next line of code

winner = &person2;

the same pointer has turned to point to the object person2.

../../_images/cpp_olioviite_2_en.png

If we want the pointer to point nowhere, we can also set it to nullptr.

This is only an introduction to the concept of pointers, and this is not meant to be a comprehensive set of learning material on this matter. The next exercise includes a finished main program that contains one pointer-type variable. Even though you do not need to make any changes to the main program, please go and examine the main program as an example of pointer use.

Pointers will be needed for several different purposes on this course, and later on, we will delve deeper into the details of using them.