On Tue, 15 Mar 2011 12:28:07 -0400, Caligo <[email protected]> wrote:



struct MyStruct{

  MyClass mc;  // 4 bytes
  int a;
  int b;
  char c;
}

class MyClass{

  MyStruct ms;  // 16 bytes
  int x;
  int y;
  char z;
}


so, 'ms' is on the heap, even though it's a struct, right? but 'mc' is just
a reference and lives on the stack, and that's why it's only 4 bytes?

btw, coming from C++, I find 'MyClass mc;' and 'MyStruct ms;' confusing; one
is a reference and the other isn't.

Yes, it's not struct vs. heap more than it is value semantics vs. reference semantics. A class is *always* pass-by-reference, and must be initialized with a constructor. A struct is allocated where it is declared (on the stack, in a class or struct, etc.), and is typically pass-by-value.

What Jonathan was saying is that classes naturally go on the heap, because that's what makes the most sense for reference semantics. Structs naturally go wherever you declare them, which can be on the stack.

A struct can also have reference semantics if it is a pImpl type struct (such as an associative array).

The point of making these distinctions is that polymorphism *requires* reference semantics. You can't use a virtual function without a reference. If you do, it is not a virtual call. This is why only classes which implement strictly reference semantics can have polymorphism in D.

-Steve

Reply via email to