Array type conversion

Mark Burnett unstained at gmail.com
Sun Apr 29 07:49:34 PDT 2007


Walter Bright Wrote:

> James Dennett wrote:
> > An array of (pointers/references to) derived is usable
> > as an *immutable* array of base (for suitable English
> > meaning of immutable, matching C++'s notion of the
> > array (equivalently, the pointers it contains) being
> > const.
> > 
> > Java has runtime checks required because it allows
> > conversion from array of Derived to array of Base,
> > and that (as you know) also uses reference semantics.
> > The conversion is widely viewed as a mistake in Java;
> > if I pass a Derived[] around, the language should
> > not silently allow one of its elements to refer to
> > a Base object.
> 
> But a derived reference can always be implicitly converted to a base 
> reference anyway. That's the point of polymorphism.

Java can allow treating D[] as a mutable B[] only because of its runtime checks.  That way it can just throw an exception when you do things like call DerivedA.foo on DerviedB.  D doesn't have this, and so it's arrays are just as type unsafe as C++'s.

You really should have a look at Chapter 24 of Marshall Cline's excellent FAQ again.  He describes the issue perhaps better than I can.

I am actually a little surprised that there is a difference in the way conversions from D[] -> B[] and D[] -> I[] work.

It seems that the easiest way to fix this is to remove the implicit D[] -> B[].  Though as James suggests, it would be safe (and useful) to pass D[] as an immutable B[] *or* immutable I[].

Mark



More information about the Digitalmars-d mailing list