const_cast: what is it good for?
i'm using the gcc compiler for windows and when running the following program
Code:
#include <iostream>
using namespace std;
int main() {
const int i = 100;
int *ip = const_cast<int *>(&i);
*ip = 110;
cout << &i << endl;
cout << ip << endl;
cout << i << endl;
cout << *ip;
}
it turns out that &i == ip but i = 100 and *ip = 110. Surely i have missed something about const_cast. Can somebody tell me more? Thanks anyway.
Do I understand you right!!!!
Quote:
Originally posted by Polymorphic OOP
Not always -- IE, if it's a non-static const of a class that is initialized on a per-object basis! :D
#include <iostream>
class x
{
const int i;
int *p;
public:
x(int val):i(val),p(0)
{
std::cout << "The value of i is " << i << std::endl;
}
void display()
{
p = const_cast<int *>(&i);
*p = 20;
std::cout << "The value of i is " << i << std::endl;
}
};
int main()
{
x ob(10);
ob.display();
return 0;
}
Output
----------
The value of i is 10
The value of i is 20