Array type conversion

janderson askme at me.com
Sat Apr 28 14:54:04 PDT 2007


Mark Burnett wrote:
> I have spent much of the last couple of weeks trying to choose a language in which to write the code for my PhD thesis (in computational physics).  I had very nearly decided on using c++, when yesterday I stumbled upon D.  So far I'm ecstatic about it's feature set.
> 
> Still there are one or two things that strike me as odd:  in particular that arrays of a derived type can be converted to an array of a base type.  As pointed out by Marshall Cline, [http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.4] this is dangerous.  Is this possibly a holdover from c++?  It is explicitly mentioned in the array page that they behave this way, so I am not convinced that is the case.
> 
> Fortunately not all of the problems associated with doing this in c++ exist in d (see attached code).  What d seems to do is treat all derived[] as base[], which is silly because if i want a base[], I would just declare it that way.  Asking for a derived[] is how I say that I  *only* want derived objects in there.
> 
> The attached code generates this output using gdc 0.23 on OSX:
> Here are the different apples we have:
> A P P L E -- Red
> A P P L E -- Red
> A P P L E -- Red
> Orange -- Orange
> A P P L E -- Red
> 
> Please, keep in mind that this test is the first d I have written, and I don't claim to understand the language.  Array type promotion just seems odd to include, and I would like to understand the motivation for doing so.

What is happening is a pointer copy from justsomefruits to lotsofapples. 
  I think that D should really enforce that the programmer writes: 
justsomefruits.ptr = lotsofapples.ptr.

Other then that though, I don't really have a problem with this type of 
conversion since it is really useful for polymorphisms.  Consider that 
you may want to write some sort of generic function that takes the 
derived class like:

void sort(Fruit [] basket)
{
	
}

Fruit [] justsomefruits; //I only have an array of fruits here because 
this particular class only wants to work on fruits (ie fruit has extra 
properties I know about).

You start to see how beneficial it can be. In my option its a neat feature.

-Joel



More information about the Digitalmars-d mailing list