Why can't structs be derived from?

Jesse Phillips jessekphillips+D at gmail.com
Tue Mar 15 11:27:55 PDT 2011


Jens Wrote:

> OK, silly me. I used a wrong example. I really did want to know about 
> non-polymorphic composition from structs via derivation. Sorry for the 
> confusion.
> 
> struct point
> {
>     int x;
>     int y;
> };
> 
> struct point3d: point
> {
>     int z;
> };

You already got your answer 'alias this' which you have dismissed as ugly. You wanted composition and I think it provides a very clean way to describe composition, especially since it looks nothing like how inheritance of classes which have polymorphic behavior. Also note the intent is to allow for multiple 'alias this' declarations, but hasn't yet been implemented.

 struct point
 {
     int x;
     int y;
 };
 
 struct point3d
 {
     point p; // I own a point
     alias this p;  // I am a composition of a point p.
     int z;
 };


More information about the Digitalmars-d mailing list