Posts

Showing posts with the label const-cast

Why does const_cast remove constness for a pointer but not for a pointer to a const?

I understand that const_cast works with pointers and references. I'm assuming that the input to const_cast should be a pointer or reference. I want to know why it doesn't remove the constness if the input is a pointer/reference to a const int? The following code works as expected. const_cast with multilevel pointers int main() { using std::cout; #define endl '\n' const int * ip = new int(123); const int * ptr = ip; *const_cast<int*>(ptr) = 321; cout << "*ip: " << *ip << endl; // value of *ip is changed to 321 } But when I try a pointer to const int or reference to const int, the value doesn't seem to change. const_cast with reference to const int int main() { using std::cout; #define endl '\n' const int i = 123; const int & ri = i; const_cast<int&>(ri) = 321; cout << "i: " << i << endl; // value in 'i' is 123 } const_cast with...