What would break if class was merged with struct

Iain Buclaw via Digitalmars-d digitalmars-d at puremagic.com
Sun May 28 02:09:39 PDT 2017


On 27 May 2017 at 20:13, Ola Fosheim Grøstad via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
> On Saturday, 27 May 2017 at 18:06:11 UTC, Stanislav Blinov wrote:
>>
>> Perhaps it wouldn't be if we were talking about new language.
>> With D, such a change falls out of "some language changes, a bit of
>> automated source updating and a little bit of breakage", and becomes "whole
>> language change, a rewrite of runtime and standard library, and breaking
>> every single project that uses D today".
>> Or did we leave behind your original question?
>
>
> No. I am talking about language semantics. Are the semantics for class and
> struct conflicting or can they be merged?
>

The semantic difference is that structs are POD records, and classes
are references (or pointers) to GC heap with inheritance (underlying
record includes fields from base classes).

For ABI, structs are compatible with C (this is documented as per
spec), and classes underlying records are compatible with C++ (don't
think this is documented, but it's certainly assumed).

Focusing on the latter point, this means that the following declarations:

    struct Something
    {
        int a;
        long b;
        char c;
    }

    class Something
    {
        int a;
        long b;
        char c;
    }

are identical to each other, apart from the latter getting a __vptr
and __monitor field.

However, for extern(D) classes, there's actually nothing stopping a D
compiler implementer from making class types more memory efficient, an
optimizing compiler could decide to re-arrange class fields as:

    class Something
    {
        long b;
        int a;
        char c;
    }

After all, we only need extern(D) to be compatible with ourselves, not
other languages.

As a side note, when I talked about D at the GNU Hackers Meeting a
number of years back, when I said that structs and classes are two
distinct types - one being POD-only, the other being a reference that
comes with the bells and whistles of OOP - I actually got a small
cheer.  This gives me a very strong impression of what C++ programmers
think of their own situation regarding struct vs class, and that we
should not be so eager to follow their design.



More information about the Digitalmars-d mailing list