A constant pointer means that the memory location will not change, not that the value at that memory location will not change.
Consider the following code. What do you think will happen?
int main()
{
int x = 5;
int y = 10;
int* px = &x;
int* py = &y;
cout << x << endl;
cout << y << endl;
cout << px << " is: " << *px << endl;
cout << py << " is: " << *py << endl;
px = py;
cout << x << endl;
cout << y << endl;
cout << px << " is: " << *px << endl;
cout << py << " is: " << *py << endl;
return 0;
}
Using const will make sure you always point to the right place.
int main()
{
int x = 5;
int y = 10;
int* const px = &x;
int* const py = &y;
cout << x << endl;
cout << y << endl;
cout << px << " is: " << *px << endl;
cout << py << " is: " << *py << endl;
px = py;
cout << x << endl;
cout << y << endl;
cout << px << " is: " << *px << endl;
cout << py << " is: " << *py << endl;
return 0;
}
Using const with Pointers in C++ was originally found on Access 2 Learn