Bug 5723 – array of base class cannot be initialized with derived types
Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2011-03-09T01:04:00Z
Last change time
2011-03-09T05:41:07Z
Assigned to
nobody
Creator
wilfried.kirschenmann
Comments
Comment #0 by wilfried.kirschenmann — 2011-03-09T01:04:46Z
Hi,
The following example
#!../dmd2/linux/bin/rdmd -unittest
class A{}
class B : A{}
class C : A{}
void main(string[] args){
B b;
C c;
A[] ar = [b, c];
}
give this error with DMD 2.052 (file is called test.d) :
./test.d(10): Error: cannot implicitly convert expression (b) of type test.A to test.C
./test.d(10): Error: cannot implicitly convert expression ([(__error),c]) of type C[] to A[]
Indeed, I agree that b cannot be converted to C.
However, I do not understand why the compiler doesn't try to convert c to A.
As a workaround, I found :
A[] ar = [b, cast(A)c];
In fact, all items except the first one have to be casted.
The other solution is :
A[] ar = [b];
ar~=[c];
This behavior is inconsistent. I would have expected :
1) all item have to be casted to A
2) no item has to be casted to A
Having just the first element to be implicitly casted is surprising.
Comment #1 by schveiguy — 2011-03-09T05:41:07Z
(In reply to comment #0)
> As a workaround, I found :
> A[] ar = [b, cast(A)c];
>
> In fact, all items except the first one have to be casted.
No, this is not the case. You can cast the whole array literal, or you can cast one element to A (any element will do).
Marking as duplicate.
*** This issue has been marked as a duplicate of issue 5498 ***