Hi,
my name is Mateo, and you are watching the course about pointers and
arrays in C++. In this module, we will talk more about implementing
indirection with user‑defined classes.
We will first go over pointers to objects, and then we will talk about
problems which arise when we use pointers as class members.
So let's get right into it. For the demonstration purposes, I will
again use this class from one of the previous modules, which is
supposed to represent complex numbers.
I only defined a single constructor, which will initialize both components with
values from the parameters. Down in the main function, I instantiated the local
object c, and printed its members to the terminal.
This is OOP 101.
Now let's create a pointer to this object c. Just like with primitive
values, I am declaring a pointer to the complex subject and
initializing it to the address of the object c.
I need to mention that this object will occupy a single block of memory on the
stack, and its size will usually be the sum of all of its members, in this
case, 8 bytes if we assume that each integer needs 4 bytes of memory. I say
usually, because that is not always the case,
but we will talk about this later.
Now let's print out all of the objects components again, but this
time I want to access them through the pointer.
Since this is just a pointer, we need to dereference it to get the
access to the real complex object. Only then we can use the dot
operator to access its member data.
It is worth mentioning that this expression without parentheses would not work.
Compiler evaluates the dot operator before the dereference operator, so this
would mean that you want to dereference the real member,
which makes no sense, since this member is not a pointer, and also
this pointer itself doesn't have any members,
it is just a pointer.
So it's crucial that we put this dereferenced pointer inside of parentheses.
But this syntax is a little bit awkward and hard to read.
That is why C++ also offers us the member of pointer
operator. Since it kind of looks like an arrow,
it is also known as arrow operator, and that's how I
usually like to refer to it myself.
So instead of dereferencing a pointer to an object
and then accessing its member,
we can simply use this arrow operator to avoid that weird notational complexity.