Why can't structs be derived from?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Mar 15 11:56:59 PDT 2011


On 03/15/2011 01:48 PM, Jens wrote:
> 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.

That's not the reason at all.

> The example I gave came from the STL so I think "frowned
> upon" is something you are picking up from long ago.

STL's mild abuses of inheritance (in the absence of something better 
such as aliases) are known and understood without being condoned at 
large. For a good account of why composition is preferable to 
inheritance, you may want to refer to 
http://www.artima.com/cppsource/codestandards3.html and the referred 
bibliography.

> 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
>
>>
>> The reason for the allegedly ugly syntax is that it's considerably
>> more general.
>
> Over-generality is a key thing that gets languages in trouble.

This is general enough to be too vacuous. We figured we need a better 
subtyping mechanism for structs and designed 'alias this' for that 
purpose. How is this getting D in trouble?

>> It is often the case that a struct defines an entity
>> that is implicitly convertible to another entity - could be an rvalue
>> vs. lvalue, a class vs. another struct vs. a primitive type, could
>> need a run-time operation etc. Inheritance would offer at best few of
>> these amenities, whereas 'alias this' offers all with a simple syntax.
>>
>
> What's wrong with conversion operators? I wouldn't use "simple" and
> "ugly" in the same sentence. I would have chosen a different design.

Please give detail on the design you would have chosen, thanks.


Andrei


More information about the Digitalmars-d mailing list