March 09, 2011 [Issue 5723] New: array of base class cannot be initialized with derived types | ||||
---|---|---|---|---|
| ||||
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@puremagic.com ReportedBy: wilfried.kirschenmann@gmail.com --- Comment #0 from Wilfried Kirschenmann <wilfried.kirschenmann@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: ------- |
March 09, 2011 [Issue 5723] array of base class cannot be initialized with derived types | ||||
---|---|---|---|---|
| ||||
Posted in reply to Wilfried Kirschenmann | http://d.puremagic.com/issues/show_bug.cgi?id=5723 Steven Schveighoffer <schveiguy@yahoo.com> changed: What |Removed |Added ---------------------------------------------------------------------------- Status|NEW |RESOLVED CC| |schveiguy@yahoo.com Resolution| |DUPLICATE --- Comment #1 from Steven Schveighoffer <schveiguy@yahoo.com> 2011-03-09 05:41:07 PST --- (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 *** -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: ------- |
Copyright © 1999-2021 by the D Language Foundation