distinguish between classes and structures

Bill Baxter wbaxter at gmail.com
Mon Dec 15 19:07:18 PST 2008


2008/12/16 Weed <resume755 at mail.ru>:
> Frits van Bommel пишет:
>>
>> Weed wrote:
>>>
>>> In C++, we had the problem - "slicing" objects.
>>> In D this problem is solved inability to inherit from structs.
>>> Without inheritance of structs many things are not possible, compared
>>> with C++.
>>> Why, instead of the complete inability to inherit, just do not make
>>> impossible to up casting struct type by value.
>>>
>>> like this:
>>>
>>> struct s1 {}
>>> struct s2 : s1 {}
>>>
>>> s1 base;
>>> s2 derr;
>>>
>>> s1* base_ptr = &derr; // ok
>>> s1 val = derr; // error
>>
>> This is why:
>>  s1 val2 = *base_ptr; // error
>
> I do not understand that it is wrong?

The problem is that base_ptr isn't actually pointing to an s1.  So by
dereferencing it and assigning to an s1 you just sliced it.  Any extra
data derr had is lost.  Any method overrides it had are lost.  So to
avoid slicing you would need to disallow dereferencing struct
pointers, or disallow pointing to a struct of a different type.

Disallowing dereferencing a struct pointer seems like it might be
possible.  But then again that's also kinda what class gives you
already.  And then you'd be left with no way to create a pointer that
can be turned back into a value!  That doesn't sound so good.

--bb


More information about the Digitalmars-d-learn mailing list