Using the const qualifier with pointers
The const
qualifier can be used to qualify pointers in several different ways. The keyword const
can be applied to the data pointed to, to the pointer itself, or both. By using the const
qualifier in these ways, C++ offers means to protect values in a program that may be meant to be initialized but never again modified. Let’s examine each of these various scenarios. We will also be combining const
qualified pointers with return values from functions to understand which of these various scenarios are reasonable to implement.
Using pointers to constant objects
A pointer to a constant object may be specified so that the object that is pointed to may not be directly modified. A dereferenced pointer to this object may not be used as an l-value in any assignment. An l-value means a value that can be modified, and that occurs on the left-hand side of an assignment.
Let’s introduce a simple example to understand the situation...