0

As I've already learned about pointers in C++, I can initialize a pointer toconst with a non-const object as the fact that this pointer is just used to read only e.g:

 int x{10};
 const int* p{ &x }; // ok. p can change addr but not the value inside it.

But the contrary is not allowed: We cannot initialize a pointer to non-const with a const object because if allowed this transgresses the rule of constness e.g:

const double Pi{ 3.14};
double* pPi{ &Pi }; // not allowed. 

Until now it is clear for me. but when it comes to Multiple-level of indirection mixed with constness, things get complicated for me. e.g:

int x{ 57 };
int* p{ &x };
const int** pp{ &p }; // why this not allowed?

As you can see above, I get compile-time error:

invalid conversion from ' int**' to 'const int**'

However if I make it this way:

int x{ 57 };
int* p{ &x };
const int* const* pp{ &p }; // ok

Or this also works:

int x{ 57 };
const int* p{ &x };
const int** pp{ &p }; // ok

Please help me to understand why allowed/not allowed. I am not intending to mess up with pointers but just to know how things can/cannot work.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Alex24
  • 600
  • 2
  • 13

0 Answers0