www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Order of interface implementations affects code

reply Andrej Mitrovic <none none.com> writes:
Should the order in which you implement interfaces have an effect in your code?
It seems to be that way when you have two functions with the same name in the
different interfaces. Here's an example:

import std.stdio : writeln;

interface Foo
{
    final void run() { writeln("foo"); } 
}

interface Bar
{
    final void run() { writeln("bar"); } 
}

class One : Foo, Bar
{
}

class Two : Bar, Foo
{
}

void main()
{
    with (new One)
    {
        run();  // writes foo
    }

    with (new Two)
    {
        run();  // writes bar
    }
}

Bug? Or legitimate working code?
Oct 14 2010
next sibling parent reply Jonathan M Davis <jmdavisProg gmx.com> writes:
On Thursday, October 14, 2010 10:14:25 Andrej Mitrovic wrote:
 Should the order in which you implement interfaces have an effect in your
 code? It seems to be that way when you have two functions with the same
 name in the different interfaces. Here's an example:
 
 import std.stdio : writeln;
 
 interface Foo
 {
     final void run() { writeln("foo"); }
 }
 
 interface Bar
 {
     final void run() { writeln("bar"); }
 }
 
 class One : Foo, Bar
 {
 }
 
 class Two : Bar, Foo
 {
 }
 
 void main()
 {
     with (new One)
     {
         run();  // writes foo
     }
 
     with (new Two)
     {
         run();  // writes bar
     }
 }
 
 Bug? Or legitimate working code?
I'd have to pull out my copy of TDPL, but IIRC, it should not be legal to call run() directly because it's ambiguous. Assuming that dmd was working correctly on this issue, it wouldn't let this code compile. I believe that you'd have to do something like Foo.run() and Bar.run() to call run(). I'd have to check TDPL to be completely sure of the syntax though. - Jonathan M Davis
Oct 14 2010
parent bearophile <bearophileHUGS lycos.com> writes:
Jonathan M Davis:

 I believe that you'd have to 
 do something like Foo.run() and Bar.run() to call run(). I'd have to check
TDPL 
 to be completely sure of the syntax though.
I think that's a compiler bug, regardless what the TDPL-Bible says :-) Bye, bearophile
Oct 14 2010
prev sibling parent Stewart Gordon <smjg_1998 yahoo.com> writes:
On 14/10/2010 18:14, Andrej Mitrovic wrote:
 Should the order in which you implement interfaces have an effect in
 your code?
No.
 It seems to be that way when you have two functions with
 thesame name in the different interfaces.
<snip> If they are normal interface functions, then if they have the same signature then they should resolve to the same function in any class that implements both. If they have the same parameters but different return types, or are final functions with the same signature, the compiler should reject any class that implements both. If one's final and the other isn't ... I guess I just don't know what's meant to happen. Stewart.
Oct 14 2010