0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 3
    Possible duplicate of [Why do const variables have to be initialized right away?](http://stackoverflow.com/questions/8440381/why-do-const-variables-have-to-be-initialized-right-away) – Ivan Aksamentov - Drop Jan 14 '16 at 23:31

3 Answers3

4

The last two statements declare the pointer itself to be constant. And you didn't give them values. Which makes them pretty darn useless, since they can never be changed (and if they're stack or class member variables, they don't even have a defined value like NULL, so they're literally useless).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
3

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.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
0

It is not a matter of good practices.
You are declaring a couple of const pointer to int and to const int (see here for further details), in both cases you must initialize them when you define them.

skypjack
  • 49,335
  • 19
  • 95
  • 187