Sign in to follow this  

Constant pointers in c++

This topic is 3728 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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").

Share this post


Link to post
Share on other sites

This topic is 3728 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this