structs, classes, interfaces - Part III, Solution

Martin Hinsch m.hinsch at rug.nl
Sat Sep 1 04:18:31 PDT 2007


The basic idea behind my solution is actually really simple. You just have to
realize that (OOP-) inheritance as it is usually done is a combination of
two different concepts - composition and polymorphism. What would happen if
we disentangled these concepts?

My suggestion would be to completely remove virtual functions from the language.
Instead use interfaces to provide ad hoc runtime polymorphism.

As before interfaces define a set of methods a class has to provide. As before
you can let a class derive from an interface to declare (and let the compiler
check) its conformance to the interface. But now this is not obligatory anymore.

There are now two fundamentally different types of pointers in the language:
a) *non-polymorphic* pointers to plain data/classes
b) *polymorphic* pointers to interfaces
At any point a pointer of type a) can be cast to a pointer of type b) *at which
point the conformance to the interface is tested*. This is easily done at 
compile time since in the non-polymorphic world all types are known.

I'll give an example:

---

class A
	{
	void foo(int a);
	}

class B
	{
	void foo(int b);
	}


interface Foo
	{
	void foo(int c);
	}

A a;
B b;

Foo * f1 = &a, f2 = &b;
f1.foo(42);		// calls a.foo

---

You could even introduce a way to construct an interface from a given class so
that existing class hierarchies could remain completely unchanged:

---

interface(B) * i = &b;

---

Internally a pointer to an interface would actually be a struct containing the
vtable and a pointer to the object which would be a tiny bit more costly than
a class reference.

Since polymorphism has now its own separate language structure composition can
be made much more powerful (similar ideas have recently been discussed for 
structs):

---

class A {...}
class B {...}

class C : A,B {...}

// syntactic sugar for

class C
	{
	A super_0;
	B super_1;
	
	use super_0;
	use super_1;
	}
	
---

I think this solves all problems I mentioned above except one, which is slicing.
To be honest I never saw the particular danger in that one in the first place.
Maybe I'm totally missing something but isn't that just another case of a lossy
cast? In that case my proposal solves that problem as well since all potentially
lossy (slicy ;-) casts can be detected at compile time and the user
warned.

I have no illusions concerning the probability of this making it into D.
Still I think it's a nice idea ;-) and I would be really interested in
hearing what people think about it.


-- 
Martin Hinsch

m.hinsch at rug.nl
+31 50 363 8097

CEES Centre for Ecological and Evolutionary Studies
Biologisch Centrum
Kerklaan 30
Postbus 14
9750 AA Haren




More information about the Digitalmars-d mailing list