Corno said:
Hi all,
There's probably a good reason why a const object can call non const
functions of the objects where it's member pointers point to.
I just don't see it. For me, that makes the the const keyword a lot
less usable.
Can anybody tell me what that good reason is?
TIA,
Corno
I suspect that you are confusing two things:
1. Whether a pointer is typed as pointing to a const object.
2. Whether a pointer is itself const.
In case 1, you cannot use the pointer to modify what is pointed to (i.e.,
you cannot change the object at the memory address contained in the
pointer). In case 2, you cannot modify the pointer itself (i.e., you cannot
change it so it points to a different memory address).
There are four possible combinations of pointer const-ness, examples of
which are given below:
// not const at all
A. TestClass * ptr;
// non-const pointer to a const object
B. const TestClass * ptr_to_const;
// const pointer to non-const object
C. TestClass * const const_ptr;
// const pointer to const object
D. const TestClass * const const_ptr_to_const;
Which category a pointer falls into depends on where the const is in
relation to the asterisk. If the const is to the left of the asterisk, that
makes it a pointer to a const object (case 1 above). If the pointer is to
the right of the asterisk, that makes it a const pointer (case 2 above).
The rules regarding these various pointer types are as follows:
Pointers to non-const objects ---- A and C above --- can be used to call
non-const member functions. However, if a object is declared to be of const
type, then a pointer to non-const objects cannot store the object's address,
i.e., an attempt to assign the address of a const object to a pointer to
non-const objects will fail to compile. Thus it is not possible to use
pointers to non-const objects to call non-const member functions on a const
object.
Pointers to const objects --- B and D above --- cannot be used to call
non-const member functions but can store the address of both const and
non-const objects.
Putting these two rules together, we see that there is no pointer that
allows you to call a non-const member function on a const object. This would
seem to be the thing that matters as far as respecting const qualifiers
goes.