Multiple class inheritance
Robert Fraser
fraserofthenight at gmail.com
Tue Feb 5 10:10:32 PST 2008
Heinz wrote:
> Hi,
>
> Is it posible to do multiple class inheritance in D?
>
> Example:
>
> class A
> {
>
> }
>
> class B
> {
>
> }
>
> class C : A, B
> {
>
> }
>
> Am i dreaming or it can be done?
The way something like this is generally done is by using interfaces.
In the _rare_ case I need true MI (that is, with implementations), I
tend to make one or both of the classes an interface with a "standard
implementation" template. So something like:
class A
{
void foo()
{
writefln("A.foo");
}
}
interface B
{
void bar();
template B_Impl()
{
void bar()
{
writefln("B.bar");
}
}
}
class C : A, B
{
mixin B.B_Impl!();
}
class D : A, B
{
override void foo()
{
writefln("D.foo");
}
override void bar()
{
writefln("D.bar");
}
}
int main(char[][] args)
{
A a = new A();
C c = new C();
D d = new D();
A a_c = c;
A a_d = d;
B b_c = c;
B b_d = d;
a.foo(); // A.foo
c.foo(); // A.foo
d.foo(); // D.foo
a_c.foo(); // A.foo
a_d.foo(); // D.foo
c.bar(); // B.bar
d.bar(); // D.bar
b_c.bar(); // B.bar
b_d.bar(); // D.bar
return 0;
}
You might want to give every interface-with-implementation an init()
method, too, to call during construction, and of course be wary of name
clashes and deep inheritance hierarchies are a lot more difficult to
manage, but, hey, there's no diamond problem.
More information about the Digitalmars-d-learn
mailing list