Multiple Inheritance

Steven Schveighoffer schveiguy at yahoo.com
Fri Sep 28 06:52:51 PDT 2007


"Olifant" <olifant at gmail.com> wrote in message 
news:fdij0a$2nup$1 at digitalmars.com...
> Say you have two interfaces: Visible and Selectable.
>
> You want that everything that inherits from Visible, has the following two 
> functions:
> SetVisible: sets it to visible or not
> GetVisible: returns what you last set it to with SetVisible
>
> You want that everything that inherits from Selectable, has the following 
> two functions:
> SetSelected: sets it to selected or not
> GetSelected: returns what you last set it to with SetSelected
>
> Some classes inherit only from Visible, others only from Selectable, 
> others from both.
>
> In C++, you can easily do this: put the implementations in the Visible and 
> the Selectable interface.
>
> How can this be done in D? I mean to avoid that everyone who inherits from 
> one of them has to write his own implementation of 
> GetVisible/SetVisible/GetSelected/SetSelected over and over again, after 
> all it's always the same.

Three ways I can think of:

1. Define a base class that inherits from one of your implementations, and 
re-implements the second implementation.  You will be re-implementing one 
implementation only once, and any derivatives that want both implementations 
can inherit from this base class.

2. You can encapsulate an implementation of each as members of the class, 
then declare the methods to call the encapsulated class' methods.

3. You can inherit from one implementation, then define an inner class that 
inherits from the other implementation.  Redirect calls to the second 
implementation to the inner class.  For example:

class VisibleImpl : Visible
{
}

class SelectableImpl : Selectable
{
}

class BothImpl : VisibleImpl, Selectable
{
   private class MySelectableImpl : SelectableImpl
   {
      // has access to BothImpl's members
   }

   private MySelectableImpl si = new MySelectableImpl;

   public override GetSelected()
   {
      return si.GetSelected();
   }

   public override SetSelected()
   {
      return si.SetSelected();
   }
}

-Steve 





More information about the Digitalmars-d mailing list