const
in C++ does not mean that a value is a constant.
const
in C++ implies that the client of a contract undertakes not to alter its value.
Whether the value of a const
expression changes becomes more evident if you are in an environment which supports thread based concurrency.
As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final
has.
eg:
#include <iostream>
int main ()
{
volatile const int x = 42;
std::cout << x << std::endl;
*const_cast<int*>(&x) = 7;
std::cout << x << std::endl;
return 0;
}
outputs 42 then 7.
Although x
marked as const
, as a non-const alias is created, x
is not a constant. Not every compiler requires volatile
for this behaviour (though every compiler is permitted to inline the constant)
With more complicated systems you get const/non-const aliases without use of const_cast
, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const
merely means that your code can't change it without a cast, not that the value is constant.