Multiple inheritance and covariant return types.

Bruno Medeiros brunodomedeiros+spam at com.gmail
Thu Aug 9 08:58:15 PDT 2007


Frank Fischer wrote:
> Hi,
> 
> I have another question on multiple inheritance. The following code does not
> work (tested with DMD 1.020 and 2.003)
> 
> ---
> interface A {}
> 
> interface B {}
> 
> interface AB: A, B {}
> 
> abstract class X {
>     abstract A func();
> }
> 
> interface Y {
>     B func();
> }
> 
> class XY: X, Y {
>     AB func() { return null; }
> }
> ---
> The compiler complains about the line 'AB func() { return null; }':
> 
> t.d(38): function t.XY.func incompatible covariant types A() and B()
> 
> but I think it should work, because AB is both, an A and a B, so the return
> type is covariant with both overridden methods. In fact, the example works
> fine, if X is an interface instead of an abstract class.
> 
> Is this a bug or is it my mistake?
> 
> Thanks,
> Frank
> 


It's not a bug.
Classes are *convertible* to interfaces that it implements but they are 
not *covariant* with said interfaces. The same thing happens for an 
interface and it's super interfaces. The interface is not covariant with 
is super interfaces, only convertible to them. (exception maybe the 
first interface). Thus in the example above AB is not both an A and B.
This behavior is different than Java and other OO languages, and is so 
for performance reasons. There are some tricks the compiler does to 
allows override as if the types were covariant, but it only works in 
some situations.


You can see it for yourself with the following code:

interface A {}
interface B {}
interface AB: A, B {}
class ABImpl : AB { }

void test() {
   writefln("%X", cast(void *) ab);
   writefln("%X", cast(void *) cast(AB) ab);
   writefln("%X", cast(void *) cast(A) ab);
   writefln("%X", cast(void *) cast(B) ab);
}

-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D


More information about the Digitalmars-d-learn mailing list