struct vs. class

Gregor Richards Richards at codu.org
Mon May 28 13:35:48 PDT 2007


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. A C struct like this:
struct Foo {
     int a, b;
}

is 100% equivalent (and passable as) a C++ class like this:
class Bar {
     public:
     int a, b;
}


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 
struct are basically syntactic sugar around functions that are defined 
taking the struct as the first argument.

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.

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.

  - Gregor Richards



More information about the Digitalmars-d mailing list