Why can't I inherit (extend) structs?

Georg Wrede georg.wrede at nospam.org
Sat Oct 14 05:49:16 PDT 2006


Derek Parnell wrote:
> On Tue, 10 Oct 2006 23:26:01 -0400, Jarrett Billingsley wrote:
> 
> 
>>"rm" <roel.mathys at gmail.com> wrote in message 
>>news:egh0bu$2155$1 at digitaldaemon.com...
>>
>>>Lionello Lunesu wrote:
>>>
>>>>It's not a big deal, since I can use composition
>>>
>>>but mixin' it in, works nicely
>>
> 
> I know I'm just dreaming but it would be very nice-to-have if one could do
> this ...
> 
>  struct Color
>  {
>     ubyte Red;
>     ubyte Green;
>     ubyte Blue;
>  }
> 
>  struct Pixel extends Color
>  {
>      ubyte Alpha;
>  }
> 
>  Pixel Z
>  Z.Red = 80;
>  Z.Blue = 125;
>  Z.Green = 0;
>  Z.Alpha = 128;
> 
> rather than 
> 
>  struct Color
>  {
>     ubyte Red;
>     ubyte Green;
>     ubyte Blue;
>  }
> 
>  struct Pixel
>  {
>      Color color;
>      ubyte Alpha;
>  }
> 
>  Pixel Z
>  Z.color.Red = 80;
>  Z.color.Blue = 125;
>  Z.color.Green = 0;
>  Z.Alpha = 128;

This could of course be implemented in D. And I think it would be useful.

struct A
{
     somefield a;
}

struct B: A
{
     otherfield b;
}

And the compiler would simply slap the A fields at the beginning of B. 
Off-hand I don't see why this would be difficult to implement. But 
implementing this would cause demands for multiple inheritance.

struct A
{
     alpha a;
}
struct B
{
     beta b;
}
struct C: A B
{
     gamma c;
}

And all's well, except when folks start doing

struct D: B A
{
}
struct E: C D
{
}

Then what? Of course we could have a restriction that says all of the 
inherited fields must have unique names. This, admittedly arbitrary 
restriction could make usage and code clearer, and expunge ambiguities.

struct Frozen_Pizza: Comestible Consumable Perishable
{
}

At this point one might start wondering whether the pros outweigh the 
cost. (And the possible cons?) I don't have an opinion on this yet. But 
doing

struct Frozen_Pizza
{
     Comestible
     Consumable
     Perishable
}

might not be all too labourious in a real-world situation, after all? 
Except when we want to use polymorphism.

Frozen_Pizza fp = new Frozen_Pizza;
Perishable p = fp;
// insert the use-before dates in p

Implementing this without any tables would be nice. Just plain structs, 
and the compiler would simply create and manipulate the derived structs 
"as usual".



More information about the Digitalmars-d-learn mailing list