Thread overview | ||||||
---|---|---|---|---|---|---|
|
February 05, 2008 Multiple class inheritance | ||||
---|---|---|---|---|
| ||||
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? |
February 05, 2008 Re: Multiple class inheritance | ||||
---|---|---|---|---|
| ||||
Posted in reply to Heinz | 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? You're dreaming. :) http://digitalmars.com/d/1.0/class.html "D classes support the single inheritance paradigm, extended by adding support for interfaces. " --downs |
February 05, 2008 Re: Multiple class inheritance | ||||
---|---|---|---|---|
| ||||
Posted in reply to Heinz | "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?
It sort of can be simulated with inner classes I think:
class A
{
}
class B
{
}
class C : A
{
B getB() { return new InnerClass(); }
private class InnerClass : B
{
// can override B functions, can access C members.
}
}
-Steve
|
February 05, 2008 Re: Multiple class inheritance | ||||
---|---|---|---|---|
| ||||
Posted in reply to Heinz | 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.
|
Copyright © 1999-2021 by the D Language Foundation