Why can't structs be derived from?

Steven Schveighoffer schveiguy at yahoo.com
Tue Mar 15 10:24:27 PDT 2011


On Tue, 15 Mar 2011 12:28:07 -0400, Caligo <iteronvexor at gmail.com> 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


More information about the Digitalmars-d mailing list