c++pointersconstantsconst-pointer

What scenario might require the use \ need of const pointer to (non-const\const) data


I understand the concept of final in Java or const in C++ for forcing constant values and allowing the compiler to enforce that on anyone using the modules you write.

I am not able to see where would you want to have a const pointer, why would you not want the pointer to change regardless of the data being constant or not:

e.g

why this?

char greetings[] = "Hello";

char * const p = greetings;  // const pointer, non-const data

const char * const p = greetings; // const pointer and const data

I cannot visualize an exmaple where you want to keep the pointer const, could it be for a file handle or something similar? or just a pointer to an object you don't want to change?


Solution

  • You may want to make a pointer itself constant for several reasons: