Inherited const when you need to mutate

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jul 10 16:19:55 PDT 2012


On Tue, Jul 10, 2012 at 04:05:51PM -0700, Walter Bright wrote:
> On 7/10/2012 4:05 PM, H. S. Teoh wrote:
[...]
> >What about the "partial const" idea I had?
> >
> >Given a class C which derives from a base class B, we may designate
> >the base class B as const, which makes every inherited field const,
> >while C itself may have mutable members. Then we can pass instances
> >of C around as B references (it's OK to implicitly convert C to
> >const(B), because the B part of C is actually const). As far as the
> >user of the B references can tell, the object is const, even though
> >the methods of C may be mutating C-specific members.
> >
> >So C could be a caching class, or whatever it is that needs mutation
> >to work, and B is its "const part" which is guaranteed by the type
> >system never to mutate.
> 
> Logical const is still mutating const members.
[...]

Not in this case. The const(B) reference does not permit any of B's
methods to mutate the members of B -- you cannot downcast a const(B)
reference to a C reference. As far as the methods of B are concerned,
the object is immutable.

The interesting part is when C's methods override B's methods: those
methods _can_ mutate the object, but not the members inherited from B.
And this does not break immutability; you cannot cast const(B) to C, so
if you start with immutable(B), it will remain immutable no matter what.
You can't call C's methods from the const(B) reference, and you can't
override B's methods with C's mutating methods without actually having a
mutable C to begin with.


T

-- 
MAS = Mana Ada Sistem?


More information about the Digitalmars-d mailing list