Search code examples
c++pointersconstants

Use a const int* const pointer to point to an int


I don't understand something here. In the following code I have defined an integer and a constant integer.

I can have a constant pointer (int* const) point to an integer. See the fourth line of code.

The same constant pointer (int* const) can not point to a constant integer. See the fifth line.

A constant pointer to a const (const int* const) can point to a constant integer. That's what I would expect.

However, the same (const int* const) pointer is allowed to point to a non constant integer. See the last line. Why or how is this possible?

int const constVar = 42;
int variable = 11;

int* const constPointer1 = &variable;
int* const constPointer2 = &constVar; // not allowed
const int* const constPointer3 = &constVar; // perfectly ok
const int* const constPointer4 = &variable; // also ok, but why?

Solution

  • You can always decide not to modify a non-const variable.

    const int* const constPointer4 = &variable;
    

    Just parse the definition: constPointer4 is a const (i.e you can't change what it is pointing to anymore) pointer to a const int (i.e. variable). This means that you can't modify variable through constPointer4, even though you can modify variable by other means.

    THe other way around (accessing a const variable through a non-const pointer), you would need a const_cast.

    Why is a pointer to const useful? It allows you to have const member functions in classes where you can guarantee to users that that member function does not modify the object.