digitalmars.D.learn - Array of derived class objects?
- "H. S. Teoh" <hsteoh quickfur.ath.cx> Mar 06 2012
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> Mar 06 2012
- simendsjo <simendsjo gmail.com> Mar 06 2012
- Andrej Mitrovic <andrej.mitrovich gmail.com> Mar 06 2012
Code:
// test.d
class A {}
class B : A {}
class C : A {}
void main() {
A[] objs = [ new B, new C ]; // line 6
}
Compiler error:
test.d(6): Error: cannot implicitly convert expression (new B) of type test.A
to test.C
test.d(6): Error: cannot implicitly convert expression ([(__error),new C]) of
type C[] to A[]
I thought D was supposed to automatically infer the most derived common
base class to assign to an array literal of different types? At least,
that's the impression I got from TDPL.
What am I doing wrong?
T
--
MAS = Mana Ada Sistem?
Mar 06 2012
On 03/06/2012 11:27 AM, H. S. Teoh wrote:Code: // test.d class A {} class B : A {} class C : A {} void main() { A[] objs = [ new B, new C ]; // line 6 } Compiler error: test.d(6): Error: cannot implicitly convert expression (new B) of type test.A to test.C test.d(6): Error: cannot implicitly convert expression ([(__error),new C]) of type C[] to A[] I thought D was supposed to automatically infer the most derived common base class to assign to an array literal of different types? At least, that's the impression I got from TDPL. What am I doing wrong? T
That's probably this bug: http://d.puremagic.com/issues/show_bug.cgi?id=5498 Luckily it has a pull request. Ali
Mar 06 2012
On Tue, 06 Mar 2012 20:27:56 +0100, H. S. Teoh <hsteoh quickfur.ath.cx> wrote:Code: // test.d class A {} class B : A {} class C : A {} void main() { A[] objs = [ new B, new C ]; // line 6 } Compiler error: test.d(6): Error: cannot implicitly convert expression (new B) of type test.A to test.C test.d(6): Error: cannot implicitly convert expression ([(__error),new C]) of type C[] to A[] I thought D was supposed to automatically infer the most derived common base class to assign to an array literal of different types? At least, that's the impression I got from TDPL. What am I doing wrong? T
I have no idea (and haven't read TDPL), but adding a new A somewhere in the array makes it work. Compiler bug..?
Mar 06 2012
You can use a cast as a workaround: A[] objs = [cast(A)new B, new C ]; This bug has been around for a while, the first time I've seen it mentioned was in the second code snippet in this blog post: http://klickverbot.at/blog/2010/11/announcing-d-support-in-swig/
Mar 06 2012









=?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> 