Newbie: copy, assignment of class instances

Steven Schveighoffer schveiguy at yahoo.com
Thu May 27 15:03:50 PDT 2010


On Thu, 27 May 2010 17:47:20 -0400, bearophile <bearophileHUGS at lycos.com>  
wrote:

> Steven Schveighoffer:
>> I have hoped that at some point, structs can be auto-composed,
>> without a vtable, but you still have to do this manually.
>
> I don't understand what you mean here :-)

I mean simple inheritance.  In C, there has always been manual  
inheritance.  You can see it with the sockaddr system, and even with the X  
toolkit widget system.

essentially, when you derive type B from type A in C++, you get this:

struct B
{
    A _a;
}

A is always put first, that way, a pointer to a B can always be used as a  
pointer to an A.

The other thing that happens is that function calls on B also use A as  
well.  This is not so easy in C, but in D it is currently quite trivial:

struct B
{
    A _a;
    alias _a this;
}

Then a call like b.methodOfA(); gets translated statically to  
b._a.methodOfA().

But there are things I don't like about this, such as you can *set* _a.   
To get around that, you define a property getter, but not a setter:

struct B
{
    private A _a;
    @property ref A a() {return _a;}
    alias a this;
}

What I would like is a common-sense approach to inheritance for structs  
that just does not allow virtual methods or interfaces, and which does not  
cast implicitly to the base (explicit cast is OK).  I think some designs  
would benefit greatly from this simple feature.  I think it's more tricky  
than I've described, but I think with some diligence it can be done.

-Steve


More information about the Digitalmars-d-learn mailing list