Constant pointers in c++

Started by
3 comments, last by Pongles 16 years, 6 months ago
Hi guys, Why is a constant pointer only able to point to a non constant value? Any help would be appreciated.
Advertisement
You need a pointer to a const value.
const int something = 10;// Ok, pointer points to a const object// Promises not to change the object it points to.const int * somethingptr = &something; // Also ok, pointer points to a const object// Promises not to change the object it points to.// It also promises not to change the pointer itself.const int * const somethingptr = &something;// Not ok. The pointer itself can't change, but what it points to can.// The compiler doesn't allow it, since you're assigning it something which is supposed to be const.int * const somethingptr = &something;


Hope this helps.
Because using the pointer you have a read only access to specific data, but that data has the ability to change via code that has the read\write scope of the addressed object.
long x = 0;const long* ptr = &x;x = 5;*ptr == 5; // true


However, if you wanted to have a pointer to constant data, you'd have to have:
const long x = 1;const long* const ptr = &x;


The data 'ptr' is addressing must be labeled as const.

EDIT: Ahh, Deventer beat me to it.

Random tidbit you may not have known, the 'this' pointer is defined as "const T* this;" in the object methods of the containing type. Hence why you can't do "this = other_object;" in some function "void T::foo()", but can change the instance data addressed via 'this' (unless of course the function is declared as "void T::foo() const").
Thanks guys!!!! I understand it now
there is more to const than you might think, checkout the link below ...

const correctness.

This topic is closed to new replies.

Advertisement