TITLE: Casting away const

(This comes from the C++ faq)

PROBLEM: What is `casting away const in an inspector' and why is it legal?


RESPONSE: cline@sun.soe.clarkson.edu (Marshall P. Cline, Ph.D.)

A: In current C++, const member fns are allowed to `cast away the const-ness of
the "this" ptr'.  Programmers use (some say `misuse') this to tickle internally
used counters, cache values, or some other non-client-visible change.  Since
C++ allows you to use const member fns to indicate the abstract/meaning-wise
state of the object doesn't change (as opposed to the concrete/bit-wise state),
the `meaning' of the object shouldn't change during a const member fn.

Those who believe `const' member fns shouldn't be allowed to change the bits of
the struct itself call the `abstract const' view `Humpty Dumpty const' (Humpty
Dumpty said that words mean what he wants them to mean).  The response is that
a class' public interface *should* mean exactly what the class designer wants
it to mean, in Humpty Dumpty's words, `nothing more and nothing less'.  If the
class designer says that accessing the length of a List doesn't change the
List, then one can access the length of a `const' List (even though the `len()'
member fn may internally cache the length for future accesses).

Some proposals are before the ANSI/ISO C++ standards bodies to provide syntax
that allows individual data members to be designated as `can be modified in a
const member fn' using a prefix such as `~const'.  This would blend the best of
the `give the compiler a chance to cache data across a const member fn', but
only if aliasing can be solved (see next question).


