TITLE: an example case for multiple inheritance

(Newsgroups: comp.lang.c++)


PROBLEM: "Jeremy L. Rosenberger"<jrosenbe@redwood.dn.hac.com>

Sure, you can implement this without multiple inheritance, but that's
not an argument for why it's not a valid example for when someone might
want to use MI. After all, you can implement an object-oriented design
without an object-oriented programming language, but that doesn't negate
the value of object-oriented designs.


RESPONSE: rmartin@oma.com (Robert C. Martin), 17 Jul 1996

MI is a valid construct with many uses.  For example, consider the
standard "Observer" Patern:

class Observer
{
  public:
    virtual void Update() = 0;
};

class Subject
{
  public:
    void Register(Observer* o) {itsObservers.Add(o);}
    void Notify()
    {
      for (Iterator<Observer*>i(itsObservers); i; i++)
        (*i)->Update();
    }
  private:
    Set<Observer*> itsObservers;
};

Now, let us say that I have a class named Door.  This class has
simple functions like "Open", "Close", etc.  Most Doors aren't observed,
and I do not wan't the 'Subject' code in applications that don't observe
doors.  Thus, Door does not inherit from Subject.

However, some Doors *are* observed.  And I wan't *those* doors to inherit
from Subject.

class ObservedDoor : public Door, public Subject
{};

Without MI this must either be implemented by manually copying the Subject
code into the Objserved door (yuk), or by delegation.  In order to use
delegation the interface of Subject must be copied into ObservedDoor by
some means.  In Smalltalk it must be copied manually (yuk).  In languages
like Java it can be a pure interface that is extended.  The ObjservedDoor
must then contain an instance of a real Subject object.  All interfaces
of Subject that were copied into ObservedDoor delegate to their corresponding
interfaces of the contained Subject object.

This is a pain in any language, and is addressed elegantly using MI.
