I have
class Fred { public: void inspect() const {}; void modify(){}; }; int main() { const Fred x = Fred(); Fred* p1; const Fred** q1 = reinterpret_cast<const Fred**>(&p1); *q1 = &x; p1->inspect(); p1->modify(); }
How could const Fred ** q1 = & p1 be done via pointer casting?
(I just read that it is possible)
Thank you for your responses. Const_cast really works for objects
#include <iostream>
gives
Inspect called Value is 7 Modify called Inspect called Value is 8 Inspect called Value is 8 Inspect called Value is 10 Inspect called Value is 10
However, for predefined types, this does not work:
int main() { const double a1 = 1.2; const double* b1 = &a1; cout << "a1 is " << (*b1) << endl; cout << "b1 is " << b1 << endl; double* c1 = const_cast<double*>(&a1); cout << "b1 is " << b1 << endl; cout << "c1 is " << c1 << endl; double* d1 = static_cast<double*>(static_cast<void*>(c1)); cout << "d1 is " << d1 << endl; cout<< "*d1 is " << *d1 << endl; *d1=7.3; cout<< "*d1 is " << *d1 << endl; cout<< "*d1 address is "<< d1 << endl; cout << "a1 is " << a1 << endl; cout << "a1 address is" << &a1 << endl; cout<< "*d1 is " << *d1 << endl; cout<< "*d1 address is "<< d1 << endl; double f1=a1; printf("f1 is %f \n", f1); }
leads to:
a1 is 1.2 b1 is 0xffbff208 b1 is 0xffbff208 c1 is 0xffbff208 d1 is 0xffbff208 *d1 is 1.2 *d1 is 7.3 *d1 address is 0xffbff208 a1 is 1.2 a1 address is0xffbff208 *d1 is 7.3 *d1 address is 0xffbff208 f1 is 1.200000
Apparently, the g ++ compiler is optimized in such a way that it replaces a1 with 1.2 whenever it finds it, so even if its value on the stack has changed, it doesn't care.
(In my case, I had problems reading directly * b1, * c1, so I had to make a double static throw - the reinterpret did not work).
Is there any way to change a1 by compiling “normally”, therefore without compiling without optimization (so that I overtake the optimization effect)?
Margu
source share