Aggregates & associations

Daniel Keep daniel.keep.lists at gmail.com
Tue Dec 18 16:53:43 PST 2007


You seem to be getting confused as to how D classes work.  In D, classes
work like they do in Java: they are *always* references.  That is,

  class Foo {}
  Foo a;

Here, a is *effectively* a pointer; it is a reference to an instance of
Foo, just like in Java.

If you want to control the layout of memory, you can use a struct.

  struct Foo
  {
      int a, b;
  }

  struct Bar
  {
      Foo foo;
      float x;
  }

  Bar b;

Here, b is exactly 12 bytes long.  &b.foo.a == &b.foo == &b.  If b is
declared as a function local, it takes up 12 bytes on the stack; if it's
declared as part of an aggregate type (like a struct, class or union,)
then it takes up 12 bytes within an instance of that type.

So, to get back to your original question, you could probably represent
aggregates as structs and associations with classes.  Note that the only
one that can represent *both* would be a struct:

  struct Baz
  {
      Foo aggregate;
      Foo* association;
  }

Currently, this is all a bit of a mess.  However, I believe that Walter
intends to (eventually) introduce scoped class members like so:

  class Foo {}

  class Bar
  {
      scope Foo aggregate;
      Foo association;
  }

So that when an instance of Bar is destroyed, its 'aggregate' member is
also destroyed (currently, this is impossible to guarantee if
'aggregate' is GC-allocated.)

But that's not really useful at this point.

Hope that helps.

	-- Daniel



More information about the Digitalmars-d mailing list