I'm new to C++ and is trying to learn the concept of pointer. I'm confused as to why the third and fourth statements results in errors while the first and second works just fine.
int *p1; //Ok
const int *p1;//Ok
int *const p1; //error: default initialization of an object of const type 'int *const'
const int *const p1; //error: default initialization of an object of const type 'const int *const'
PS: I understand that it is good practice to initialise all pointers when declaring them or at least set their value to nullptr or 0. I asked this question because I want to understand the concept behind it.
Non-class types with top-level const must be initialized in the definition.
Lines 3 and 4 have top-level const
, in the sense that p1
cannot be modified. Line 2 does not have top-level const
; p1
can be modified but the int
it points to cannot.