Inheritance of purity

Jonathan M Davis jmdavisProg at
Sun Feb 26 04:17:53 PST 2012

On Sunday, February 26, 2012 13:02:14 deadalnix wrote:
> Thinking more about this, I did notice that I almost never do a const
> and a non const version of the same function when coding (either the
> functionality require const or it doesn't, so the const and non const
> version will do something very different, which is confusing).
> Is it common ? If it is, it open the door to limiting override
> possibilities when it come to const.non const, with the advantage of
> being able to infer const in way more place than it is actually. I could
> expand about that.

It's common for some stuff. A classic example would be iterators (or ranges). 
If you have a const reference or pointer to a container, then the iterator (or 
range) that you get out of it must give you const access to the elements, 
whereas a non-const reference or pointer to a container should be able to give 
you an iterator or range with mutable access to the elements.

One place that overloading on const in D could be very useful where it's of 
little use in C++ would be for caching. If you called a non-const version of a 
function, then the result could be cached (or the cached result used if the 
result isn't dirty), whereas while the const one could also use the cached 
version if it wasn't dirty, if the cached value was dirty, it would have to do 
the calculation without caching the result, since the object is const, and so 
it can't alter the cached value.

It _is_ true, however, that there are a lot of cases where it makes no sense 
to have both a const and non-const version of a function.

- Jonathan M Davis

More information about the Digitalmars-d mailing list