fork(1) download
  1. #include <iostream>
  2.  
  3. struct wrapper
  4. {
  5. wrapper() : data(6) { }
  6. void modify(int value) const
  7. {
  8. // this->data = value; // compile error: this is a pointer to const
  9. const_cast<wrapper*>(this)->data = value; // OK as long as the type object isn't const
  10. }
  11. int data;
  12. };
  13.  
  14. int main()
  15. {
  16. int i = 6; // i is not declared const
  17. const int& ci = i;
  18. const_cast<int&>(ci) = 42; // OK: modifies i
  19. std::cout << "i = " << i << std::endl; // OK, will be 42
  20.  
  21. const int j = 6; // j is declared const
  22. int* pj = const_cast<int*>(&j);
  23. *pj = 42; // undefined behavior!
  24. std::cout << "j = " << j << std::endl; // can be both 6 or 42
  25.  
  26. wrapper w;
  27. w.modify(42);
  28. std::cout << "w.data = " << w.data << std::endl;
  29.  
  30. const wrapper cw;
  31. cw.modify(42); // undefined behavior!
  32. std::cout << "cw.data = " << cw.data << std::endl; // can be both 6 or 42
  33.  
  34. void (wrapper::*mp)(int) const = &wrapper::modify; // pointer to member function
  35. const_cast<void(wrapper::*)(int)>(mp); // compiler error: const_cast does not work on function pointers
  36. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:35:39: error: invalid use of const_cast with type 'void (wrapper::*)(int)', which is not a pointer, reference, nor a pointer-to-data-member type
   const_cast<void(wrapper::*)(int)>(mp); // compiler error: const_cast does not work on function pointers
                                       ^
stdout
Standard output is empty