Simulating Multiple Inheritance

dsimcha dsimcha at yahoo.com
Thu Oct 28 08:28:14 PDT 2010


I've just found a new D-specific design pattern for simulating non-virtual
multiple inheritance by abusing inner classes and alias this.  Here's an example:

class Foo {
    uint num = 2;
}

class Bar {
    uint num = 3;
}

class Outer : Foo {

    class Inner : Bar {}

    Inner inner;

    this() {
        inner = new Inner;
    }

    alias inner this;
}

Basically, this satisfies all of the requirements for simulated multiple
inheritance:

1.  An Outer can be implicitly converted to either a Foo or a Bar.

2.  It obtains both interface and implementation from both Foo and Bar.

3.  The methods of Outer that override stuff from Foo have access to
Bar-related stuff and vice-versa.

Should this be listed somewhere as D's answer to lack of multiple inheritance?
 I find it very cool that the language is expressive enough to reasonably
simulate MI.


More information about the Digitalmars-d mailing list