Differing implementations for a function in two interfaces

Derek Parnell derek at psych.ward
Sat Apr 15 19:33:58 PDT 2006


On Sun, 16 Apr 2006 11:43:41 +1000, BCS <BCS_member at pathlink.com> wrote:

> In article <e1s2sr$n4s$1 at digitaldaemon.com>, Hasan Aljudy says...
>>
>> What you want is exactly what polymorphism is designed for. I really
>> don't understand what's your problem.
>>
> I don't believe that D can solve the following problem. I can see  
> several way to
> get a _similar_ effect but all have substantial penalties involving code
> complexity, speed or maintainability/extensibility
>
> If you can use you suggested approach to solve this problem I would be  
> pleased
> to see it.
> ---------------
> You are given this (you may not modify it)
>
> interface I {int get();}
> interface J {int get();}


I understood that an 'interface' was just a way of stating that the  
methods named in it must be implemented by any class that is derived from  
the interface. In other words, that the class must implement a method with  
the same name and parameter signature. So if two interfaces have the same  
method defined, then the class that is derived from both must define a  
method (one method) of the same name etc...


> 1) You need to make a class C that implements both I and J that has  
> different
> action for I.get and J.get.

You can't do this in one class. I guess you can do ...

   class IC: I
   {
      int get(){ return 1; }
   }

   class JC: J
   {
      int get(){ return 2; }
   }

   class C
   {
       IC i;
       JC j;

       . . .
   }

   C c = new C;
   c.i.get;	// must call the appropriate I.get even if c is of a derived  
type.
   c.j.get;	// must call the appropriate J.get even if c is of a derived  
type.


> 2) Classes derived from C must be able to override the action of both  
> I.get and
> J.get

But there are no actions defined for these interface methods, just  
signatures. There is nothing to override.

> 3) Given an instance, c, of the class C, the following statements must  
> work.
> I i = c;
> i.get	// must call the appropriate I.get even if c is of a derived type.
> J j = c
> j.get	// must call the appropriate J.get even if c is of a derived type.
>
> 4) Converting a C object to an I or J interface must not rely on the  
> overloading
> of the cast operation (e.i. "I i = c;" must not call any methods)
>
> 5) Must be simply extendable to interfaces with lots of function (one  
> more
> function in I must not require more than one function be defined to keep  
> C up to
> date)

It seems that 'interface' in D means something different from what you  
mean by the term.

-- 
Derek Parnell
Melbourne, Australia



More information about the Digitalmars-d-learn mailing list