Differing implementations for a function in two interfaces

Hasan Aljudy hasan.aljudy at gmail.com
Sat Apr 15 13:48:14 PDT 2006


Hasan Aljudy wrote:
> BCS wrote:
> 
>> In article <e1riem$3jd$1 at digitaldaemon.com>, Hasan Aljudy says...
>>
>>> I didn't read/undertstand your entire post, but I think what you're 
>>> trying to achieve here can already be achieved through polymorphism.
>>>
>>> I think you just need to redeisgn the classes a little bit.
>>>
>>>
>>
>> I don't think that would (always) work. Consider the following:
>>
>> interface IA
>> {
>> int get();
>> }
>>
>> interface IB
>> {
>> int get();
>> }
>>
>> class C : IA, IB
>> {
>> public int i;
>> // illegal but ...
>> int get() { return i+1; } // get for IA
>> int get() { return i+2; } // get for IB
>> }
>>
>> void main()
>> {
>> auto obj = new C;
>> IA a = obj;
>> IB b = obj;
>>
>> obj.i = 0;
>> writef(a.get, \n);    // should print 1
>> writef(b.get, \n);    // should print 2
>>
>> obj.i = 2;
>> writef(a.get, \n);    // should print 3
>> writef(b.get, \n);    // should print 4
>>
>> }
>>
>> Both "a" and "b" are actually pointing to obj but calls to "get" using 
>> them are
>> supposed to differ. Some types of this problem could be handled by 
>> deriving
>> classes from C but not when the interfaces must actually be dealing 
>> with the
>> same object.
>>
>> Cases like this could really happen if someone needs to implement two 
>> interfaces
>> from different libraries in the same class.
>>
>>
> 
> I know, I'm saying, you can do this using polymorphism, along with a 
> redesign, invloving decoupling the get method from the C class.
> 
>     class C
>     {
>         protected int i;
>     }
> 
>     abstract class CGetter
>     {
>         abstract int get( C c );
>     }
> 
>     class CA : CGetter
>     {
>         int get( C c )
>         {
>             return c.i + 1;
>         }
>     }
> 
>     class CB : CGetter
>     {
>         int get( C c )
>         {
>             return c.i + 2;
>         }
>     }
> 
>     void main()
>     {
>         auto obj = new C;
>         CA a = new CA;
>         CB b = new CB;
> 
>         obj.i = 0;
> 
>         writefln(a.get(c));    // should print 1
>         writefln(b.get(c));    // should print 2
> 
>         obj.i = 2;
>         writefln(a.get(c));    // should print 3
>         writefln(b.get(c));    // should print 4
>     }
> 
> 
> 
> A bit more complicated (for this simple example), but you're doing the 
> same thing: creating new entries in a vtable, to choose different 
> functions at runtime.
> 

ouch, typo, replace a.get(c) with a.get(obj)

         obj.i = 0;

         writefln(a.get(obj));    // should print 1
         writefln(b.get(obj));    // should print 2

         obj.i = 2;
         writefln(a.get(obj));    // should print 3
         writefln(b.get(obj));    // should print 4



More information about the Digitalmars-d-learn mailing list