Why can't structs be derived from?

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


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;

Cheers,
- Daniel


More information about the Digitalmars-d mailing list