0

I have this Type const* p method. Is it sure that p's pointee, *p will never be modified ?

Same thing with Type const* const q.

kiriloff
  • 25,609
  • 37
  • 148
  • 229
  • Related, not same question. i am wondering whether i can modify pointee of p if p is a `Type const* p`. Tks. – kiriloff Apr 21 '13 at 11:08

2 Answers2

2

Type const* p is a pointer to const object with type Type. To be read left to right, with pointer pointing to type defined by everything before the star. The same way, Type const* const q is a const pointer to a const object with type Type.

Also, *p cannot be modified through p. p is defined so as to const-point to *p and promise not to modify it. However, *p, p's pointee, can be modified by any other pointer pointing at it.

For example, we can have

Type t;
Type const* pc = &t;
Type *pnc = &t;

pc promises not to alter t, pnc does not. Let's say class Type bears a const inspect() const method and a non-const mutate() method. Then we could have

pc->inspect();
pnc->inspect();
pnc->mutate();

whereas this one would rise compiler's error:

pc->mutate(); 

Type const* const q is a pointing to a const object and *q cannot be modified through q, just like with p. What is more, pointer q cannot be modified: it cannot be assigned a pointee a second time.

Also, although this may sounds very strange, you are allowed to change in code the object of type Type pointed by pointer Type const* p -- but not through p.

kiriloff
  • 25,609
  • 37
  • 148
  • 229
0

Yes it can't be modified but, it will only guarantee that the variable the pointer points to will be constant and it is not the same thing as Type const* const q which also guarantees that pointer is constant

fatihk
  • 7,789
  • 1
  • 26
  • 48