The pointer variables that we have seen so far are explicit pointers. If you want to see what such a variable points to, you use the * operator. C++ also supports implicit pointer variables, called reference variables. Statement
int x = 1; int& v = x; v = 20;puts the address of variable x into v. Any time you use v, you implicitly use x instead. So the assignment of 20 to v actually stores 20 into x. An implicit * is added.
Notice that you do not explicitly write &x in the line that creates v. That is also done implicitly.
If you create an integer
const int size = 50;then it is clear that you cannot change size. But what about the following?
int x = 25; const int* p = &x;Does the const designator indicate that you cannot change p or that you cannot change *p? The definition of C++ says that you cannot change *p. So
int x = 25; const int* p = &x; *p = 3;is not allowed. More precisely, if p is marked const, then you cannot use p to change *p. You are still allowed to write
int x = 25; const int* p = &x; x = 3;
You are allowed to store a different memory address into a const pointer. For example,
int x = 50; int y = 100; const int* p = &x; ... p = &y;is allowed.
If you want to make the pointer variable itself fixed, write const after the type. For example, if q is created as follows
int n = 0; int const * q = &n;
indicates that variable q itself cannot be changed, but *q can be changed. To make q and *q constant, writeconst int const * q = &n;