Why can't structs be derived from?

Simen kjaeraas simen.kjaras at gmail.com
Wed Mar 16 14:24:34 PDT 2011


On Wed, 16 Mar 2011 22:05:49 +0100, Steven Schveighoffer  
<schveiguy at yahoo.com> wrote:

> On Wed, 16 Mar 2011 16:49:53 -0400, Simen kjaeraas
> <simen.kjaras at gmail.com> wrote:
>
>> On Wed, 16 Mar 2011 16:23:47 +0100, Steven Schveighoffer  
>> <schveiguy at yahoo.com> wrote:
>>
>>> struct Point2 {
>>>     int x, y;
>>>     void draw(Canvas c) {...}
>>> }
>>>
>>> struct Point3 : Point2 {
>>>     int z;
>>>     void draw(Canvas c) {...}
>>> }
>>>
>>> Point3 p3;
>>> Point2 *p2 = &p3;
>>>
>>> // what does this do?
>>> p2.draw(c);
>>
>> Nothing. You should got a type error upon attempting to assign a p3* to  
>> a p2*.
>
> We are assuming struct inheritance works here, as in C++.  In C++ I can  
> the address of a derived object to a base class pointer without a cast.

And I was assuming we tried to fix C++'s problems in that regard. If we
were to use the rule I chose, the slicing problem is moot.


> This exact code compiles in C++ except for putting semi-colons after the  
> structs (BTW, I have to mention that I freaking LOVE D for eliminating  
> that)

I know. It's my number one C/C++ mistake, and same for all students I've
had to help (as well as some teachers :).


> and change p2.draw(c) to p2->draw(c).
>
> Even if you say that you shouldn't be allowed to do that, then you are  
> going to have complaints as to why it's different from C++...

We already have that. Just the other day, some guy named Jens complained
that D structs can't be derived from.


> The point is, if we allow inheritance on structs, it causes more  
> confusion to people who expect certain things from inheritance than it  
> beautifies syntax.

I agree. I also prefer alias this, both for its flexibility and its
distinctiveness. I just felt that the slicing problem is trivially fixed,
and thus need not be a part of the discussion.

-- 
Simen


More information about the Digitalmars-d mailing list