How to pointer-cast Foo** to const Foo** in C++

c++, casting, pointers

Solution

You want `const_cast`.

Problem

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 would it be possible to do the const Fred** q1 = &p1 via pointer-casting? (I have just been reading that this might be possible) Thank you for your answers. The const_cast works indeed for objects ``` #include <iostream> #include <stdio.h> using namespace std; class Fred { int a; public: Fred(){}; Fred(int a_input) { a = a_input; }; void inspect() const { cout << "Inspect called"<< endl; cout << "Value is "; cout << a << endl; }; void modify() { cout << "Modify called" << endl; a++; }; }; int main() { const Fred x = Fred(7); const Fred* q1 = &x; Fred* p1 = const_cast<Fred*>(q1); p1->inspect(); p1->modify(); p1->inspect(); x.inspect(); *p1 = Fred(10); p1->inspect(); } ``` 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 it 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); } ``` is resulting in: ``` 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 optimizes such that it replaces a1 by 1.2 whenever it finds it, so, even if its value on the stack has changed, it does not care. (In my case I had problems with directly reading the *b1, *c1, so I had to do the double static cast - the reinterpret cast did not work). Is it any way to really change a1, compiling "normally", therefore not compiling without the optimization (so I overtake the optimization effect)?

Original source