Jump to content
  • Advertisement
Sign in to follow this  
ciranmc

Constant pointers in c++

This topic is 3947 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

Hi guys, Why is a constant pointer only able to point to a non constant value? Any help would be appreciated.

Share this post


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

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!