struct vs. class

Martin m_dot_hinsch at rug.nl
Mon May 28 14:36:51 PDT 2007


Gregor Richards Wrote:

> Martin wrote:
> > Inspired by the recent discussion about iterator structs/classes I wanted to ask - what's the design rationale behind having both structs and classes? In C++ the necessity was given by backwards compatibility but that doesn't apply to D of course. 
> > The only principal differences I can see (I'm not a D programmer (yet), so please correct me if I'm wrong) are a) that structs don't contain run-time meta information (a pointer to a vtable or however that works) and b) that struct variables are statically allocated as opposed to class variables which always seem to be pointers into dynamic memory.
> > Somehow this looks really unorthogonal to me. Especially b) I find strange, can somebody explain the reason for this?
> > 
> > cheers
> > Martin
> 
> Firstly, your assertion about C++ is incorrect. C++ doesn't have both, 
> classes are just structs that are private by default, structs are just 
> classes that are public by default.

Yes, I know that - still, formally they are two different things (albeit very similar).
 
> Structs in D are very light-weight. A struct is just a conglomeration of 
> data. Passing a struct which contains two ints is exactly like passing 
> the two ints, but syntactically less gross. Functions defined within a 

Isn't that the same as a tuple, then?

> struct are basically syntactic sugar around functions that are defined 
> taking the struct as the first argument.

Hmmm, but in principle the same holds for class functions. The only difference is that there is an additional lookup rule since they are virtual per default.

> Classes are properly object oriented: They have hierarchies, methods are 
> virtual, etc. As such, they're (comparably to structs) heavyweight: They 
> have classinfo, are allocated on the heap, method calls require looking 
> in a vtable, etc.
> 

There is no reason why structs couldn't have hierarchies as well.

> Your 'b' statement is incorrect. In both cases, the data is allocated 
> where the struct/class is allocated. Just classes are usually on the 
> heap, structs are generally on the stack.
> 
Oh, then I got that wrong. I thought there was no way in D to create a class variable on the stack.

Anyways, my point is that really the only *necessary* difference between structs and classes is that the latter can have run-time type information and virtual functions. Everything else is just convenient syntactical sugar for which there is no technical reason to not add it to structs as well.
And if that's the case I start to wonder if it's not possible to unify the two concepts somehow.

cheers
Martin



More information about the Digitalmars-d mailing list