forbid field name conflict in class hierarchy

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 15 12:32:07 PST 2010


On Monday 15 November 2010 11:44:11 spir wrote:
> On Mon, 15 Nov 2010 09:45:26 -0800
> 
> Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > On Monday, November 15, 2010 06:00:33 Manfred_Nowak wrote:
> > > Jonathan M Davis wrote:
> > > > Having public fields shadow each other is problematic.
> > > 
> > > Detecting a problem requires having a model.
> > > What does your model look like?
> > 
> > You're going to have to be more specific in your question than that. It's
> > not at all clear what you're asking.
> > 
> > Public and protected functions use polymorphism. Public and protected
> > member variables do not. So, it becomes error prone to have public or
> > protected member variables which shadow each other. It becomes easy to
> > end up in a situation where you're not using the one that you think that
> > you're using - especially when code gets changed.
> 
> True. There is an issue in the static model of OO, with class hierarchy:
> methods are dispatched, data fields are not. If there are "same" fields
> (same name & type), then the one of the superclass is used. The only safe
> alternative would be to have runtime dispatch of fields like of methods,
> but this is indeed costly.
> 
> (This "staticity" also leads to the side-effect that one cannot write
> generic routines which variables (from parameters or result of calls) have
> the superclass as declared type but also use subclass fields. To be able
> to do it, I end up adding subclass fields to the superclass. I know it's
> wrong, but haven't found the right way to do it. I don't feel like
> "downcasting" most variables in most routines.)

I'm not sure that pure OO would even allow for public variables. I do really 
have to wonder what you're doing though that you feel the need to access 
subclass fields using super class references. That just screams that it shouldn't 
be a public member variable (and truth be told, public member variables are 
generally considered bad practice except in simple objects - which would 
generally be structs in D). And if you really need the subclass type, then you 
should be using the subclass type, not the super class type. Also, return types 
are covariant, so you can return a subclass from overridden functions instead of 
the super class like the function which was overridden does. Maybe that would 
help. It would depend on what exactly you're doing though.

- Jonathan M Davis


More information about the Digitalmars-d mailing list