SubClass[] does not implicitly convert to SuperClass[], why?

Tobias Pankrath via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 20 00:34:47 PST 2015


On Friday, 20 February 2015 at 08:25:49 UTC, rumbu wrote:
> On Friday, 20 February 2015 at 07:57:17 UTC, Tobias Pankrath 
> wrote:
>> What's the reason behind this design?
>>
>> class Super {}
>> class Sub : Super {}
>>
>> void foo(Super[] sup) {}
>>
>> void main() {
>>    Sub[] array;
>>    foo(array); // error, cannot call foo(Super[]) with 
>> arguments (Sub[])
>> }
>
> Just make the sup parameter const:
>
> void foo(in Super[] sup) {}
>
> http://dlang.org/arrays.html (end of the page):
>
> A dynamic array T[] can be implicitly converted to one of the 
> following:
> const(U)[]
> const(U[])
> Where U is a base class of T.
>
> The reson behind the design - I wonder about that also.

Thanks, didn't know that. Makes sense.

Probably the reason is:

void foo(Super[] sup) { sup[3] = new AnotherDerivedClass(); }

After foo returns the slice passed as argument would violate its 
invariant.


More information about the Digitalmars-d-learn mailing list