C++ Pointers – Why Can Pointer-to-Const Point to Non-Const Object?

c++const-correctnesslanguage-designpointers

//Example 1
const double pie = 3.14;   // const object
const double *cptr = &pie; // pointer-to-const to const object
double *ptr = &pie;        // ERROR - pointer-to-non-const to const

//Example 2
double pie = 3.14;         // non-const object
const double *cptr = &pie; // pointer-to-const to non-const object
double *ptr = &pie;        // pointer-to-non-const to non-const object

Initially I though pointer-to-const to non-const object is allowed because it just mean
pointer-to-const won't change non-const object.

But i just read in c++ book
that the reason pointer-to-const to non-const object is allowed because there's no
way for pointer-to-const pointer to really know whether the object it points to is const,
so it treat the object it points as const
but by the same logic, pointer-to-non-const would treat const object as non-const object
but compiler will throw error at compile time.

Am I missing something here?

Best Answer

Declaring a const says, "The value of this variable should not change."

Declaring a pointer to a const says, "I have no intention of changing the variable I am pointing to".


Question 1: why do you get an error when a pointer to a variable is assigned the address of a const?

// Example 1
const int i = 0;
int * p = &i;        /* Error */

Answer: Because the first line says, "please guarantee that the value of i doesn't change", but in the second line the compiler can no longer make that guarantee - the type information on the pointer p is not strict enough to tell the compiler not to allow changes to the pointed-to value i.


Question 2: why don't you get an error when a pointer to a const is assigned the address of a variable?

// Example 2
int j = 0;
const int * q = &j;  /* No error */

Answer: Because a pointer to a const says, "please guarantee that the value of j does not change via q". Note that the via q is important because the pointer to const declaration doesn't mean that the value pointed to must be a constant, only that whoever is using the pointer can't use the pointer to change the value.