Why can't structs be derived from?

Daniel Gibson metalcaedes at gmail.com
Tue Mar 15 12:36:31 PDT 2011


Am 15.03.2011 20:24, schrieb Jens:
> Daniel Gibson wrote:
>> Am 15.03.2011 19:48, schrieb Jens:
>>> Andrei Alexandrescu wrote:
>>>> On 3/15/11 12:55 PM, Jens wrote:
>>>>> Steven Schveighoffer wrote:
>>>>>> That's all there is.  Structs do not have inheritance, only alias
>>>>>> this.
>>>>>
>>>>> Why don't they though? Inheritance does not have to mean
>>>>> polymorphic. It can mean composition, like in C++. I don't
>>>>> understand the reason for such ugly syntax.
>>>>
>>>> Using inheritance for composition is frowned upon in C++ for good
>>>> reasons. If you want composition, the best is to use composition.
>>>
>>> It was frowned upon early on because the compiler implementers didn't
>>> have their acts together and the resulting objects layout could not
>>> be relied upon. The example I gave came from the STL so I think
>>> "frowned upon" is something you are picking up from long ago.
>>>
>>> Composition means access through the members rather than direct
>>> access:
>>>
>>> struct point
>>> {
>>>     int x;
>>>     int y;
>>> };
>>>
>>> struct point3d
>>> {
>>>     point pt;
>>>     int z;
>>> };
>>>
>>> ...
>>>
>>> point3d mypoint;
>>> mypoint.pt.x = 3; // ugly
>>>
>>
>> This is why you add "alias pt this;" to point3d. So you can write
>>  mypoint.x = 3;
>>
> 
> Still ugly though. 
> 

I don't think so. It makes obvious what happens: a composition - *not* an
inheritance - with syntactic sugar that allows one to omit the .pt in
mypoint.(pt.)x - as long as mypoint doesn't have a member x itself.

Allowing inheritance syntax on structs would only lead to confusion - especially
for people coming from C++.

Cheers,
- Daniel


More information about the Digitalmars-d mailing list