For me, it seems that you have confusion about what a pointer does, and where *
belongs.
Pointer is a special type of object that points to another object, not from an object.
Pointer can be declared like this:
int *a;
Here, *
specifies that a
is a pointer. Pointer types are distinct type from the type of the object that they point to.
But what a
points to is indeterminate. You need to assign an address to make a
point to something. To do that, let's make an integer (here initialized with value 2
):
int b = 2;
And let a
point to b
:
a = &b;
Here, the unary &
operator is used to take b
's address. And you assign this to a
, and then a
points to b
.
Of course, a pointer can also be initialized. The statements above can be replaced to:
int b = 2;
int *a = &b;
Then, how do you get b
's value from a
? You can do that by dereferencing a
:
std::cout << *a << std::endl;
This prints 2
. The unary operator *
is used here to dereference a
. This *
is different from the *
used to declare a
above and should not be confused.
++*a;
This increases b
. b
now has value 3
.
You can make a
point to a different object by assigning another address:
int c = 3;
a = &c;
Now a
points to c
instead of b
.
You can copy a pointer, which will point to the same object:
int *d = a;
Now d
points to c
, which a
also points to.
References are different from pointers:
int &e = b;
&
is used here to specify e
is a reference. This &
is different from the &
used to take an address and should not be confused. Here, e
refers to b
.
They refer to an object and always act as if they were that object:
++e;
This increases b
. b
now has value 4
.
Unlike pointers, references must always refer to an object:
int &f; // error
A reference can also refer to a pointer:
int *&g = a;
g
refers to a
.
But a pointer cannot point to a reference:
int &*h = &e; // error