When I write this code fragment, after modifying the value of const variable i through pointer I am getting value of i as 10, but when i print *ptr i get 110.
const int i = 10;
int *ptr = const_cast<int *>(&i);
*ptr = *ptr + 100;
cout << "i: " << i << "\t*ptr: " << *ptr << endl;
I am getting output i: 10 and *ptr :110.
And in this case I am having a const variable x as a member variable of class Base. And through function show() I am able to modify the value of const variable x i.e when I print x and *ptr I get changed value in both.
class Base
{
public:
const int x;
Base(int i) : x(i) {}
virtual void show()
{
int *ptr = const_cast<int *>(&x);
int *ptr = const_cast<int *>(&x);
cout << "In Base show:\n";
cout << "Address of x : " << &x << endl;
cout << "Address in ptr : " << ptr << endl;
cout << "value in x : " << x << endl;
cout << "value in ptr : " << *ptr << endl;
*ptr = *ptr + 10;
cout << "After modifying " << endl;
cout << "value in x : " << x << endl;
cout << "value in ptr : " << *ptr << endl;
}
};
class Derived : public Base
{
public:
Derived(int i) : Base(i){}
virtual void show()
{
int *ptr = const_cast<int *>(&x);
cout << "In Derived show:\n";
cout << "Address of x : " << &x << endl;
cout << "Address in ptr : " << ptr << endl;
cout << "value in x : " << x << endl;
cout << "value in ptr : " << *ptr << endl;
*ptr = *ptr + 10;
cout << "After modifying " << endl;
cout << "value in x : " << x << endl;
cout << "value in ptr : " << *ptr << endl;
}
};
int main()
{
Base bobj(5),*bp;
Derived dobj(20), *dptr;
bp = &bobj;
bp->show();
bp = &dobj;
bp->show();
return 0;
}
The output which I am getting is this
In Base show:
Address of x : 0x7fff82697588
Address in ptr : 0x7fff82697588
value in x : 5
value in ptr : 5
After modifying
value in x : 15
value in ptr : 15
In Derived show:
Address of x : 0x7fff82697578
Address in ptr : 0x7fff82697578
value in x : 20
value in ptr : 20
After modifying
value in x : 30
value in ptr : 30
Can anybody help.