Struct "inheritance"

Simen Kjærås simen.kjaras at gmail.com
Sat Feb 4 04:06:18 PST 2012


On Sat, 04 Feb 2012 12:38:30 +0100, Vidar Wahlberg <canidae at exent.net>  
wrote:

> Good day.
>
> I know "inheritance" is a misleading word as there's no such thing when  
> it comes to structs, but I couldn't think of a better description for  
> this problem:
>
> Let's say I got a struct for a location on a 2-dimensional plane:
> struct Point {
>    int x;
>    int y;
> }
> Further I also need to represent a location in a 3-dimensional space:
> struct Coordinate {
>    int x;
>    int y;
>    int z;
> }
> If these were classes instead I could simply make Coordinate inherit  
> from Point and only add "int z;". This would also make the thing I'm  
> trying to achieve much easier; Consider I have a method that does  
> something nifty with "x" and "y", I'd like this method to handle both  
> "Point" and "Coordinate", if they were classes it would be fairly simple:
> int somethingNifty(Point p) {
>    return p.x + p.y;
> }
>
>
> So why not just use classes? I've understood it as there may be a  
> performance gain by using structs over classes, and in my program Point  
> and Coordinate are used heavily.
>
> Obviously I'm fairly new to both D and structs, I have plenty Java and  
> some C++ experience (I've avoided using structs in C++) and I have "The  
> D Programming Language" book by Andrei which I'm happy to look up in,  
> although I've failed to find an answer to this question in the book, in  
> this newsgroup and on the net.
> I would greatly appreciate if someone could give me a nudge the the  
> right direction.

It seems that what you want is alias this:

struct Point {
     int x;
     int y;
}

struct Coordinate {
     Point pt;
     int z;
     alias pt this;
}

void foo( Point p ) {}

void main( ) {
     Coordinate c;
     foo( c );
     c.x = 3;
     c.y = 4;
     c.z = 5;
}


More information about the Digitalmars-d-learn mailing list