[Issue 5723] New: array of base class cannot be initialized with derived types

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Mar 9 01:07:48 PST 2011


http://d.puremagic.com/issues/show_bug.cgi?id=5723

           Summary: array of base class cannot be initialized with derived
                    types
           Product: D
           Version: D2
          Platform: x86_64
        OS/Version: Linux
            Status: NEW
          Severity: normal
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: wilfried.kirschenmann at gmail.com


--- Comment #0 from Wilfried Kirschenmann <wilfried.kirschenmann at gmail.com> 2011-03-09 01:04:46 PST ---
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.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list