0
  • When and why const_cast is necessary for converting non-const to const types?

  • Why in the following code const-cast is necessary for line 8 and unnecessary for lines 6, 7, 9?

int a = 27;                                     // 1
int const b = 412;                              // 2
int* pa = &a;                                   // 3
int const c = a;                                // 4
int d = b;                                      // 5
int const* p1 = pa;                             // 6
int* const* p2 = &pa;                           // 7
int const** p3 = const_cast<int const**>(&pa);  // 8
int const* const* p4 = &pa;                     // 9

Please answer both questions or provide a link to the explanation:)

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Roma
  • 55
  • 8
  • 1
    https://en.cppreference.com/w/cpp/language/implicit_conversion vs. https://en.cppreference.com/w/cpp/language/const_cast – Werner Henze May 10 '20 at 12:05
  • [const pointer pointer conversion](https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion) – Eljay May 10 '20 at 12:17
  • *p3 = &b; *pa = 1; // what is the value of b? – QuentinUK May 10 '20 at 13:50
  • Concerning _When and why const_cast is necessary for converting non-const to const types?_ an [**mcve on coliru**](http://coliru.stacked-crooked.com/a/fb663217ff7ee156). This resembles a real-world issue I once got because the non-const version of a getter was used for class-internal modifications and hence `protected`. The `public`getter was `const`. In SO, I saw that I'm not the only one who stumbled over this although it's probably somehow exotic. – Scheff's Cat May 10 '20 at 14:10

0 Answers0