dup field in sub-class should be reported by the compiler

Sean Kelly sean at f4.ca
Mon Aug 13 15:42:20 PDT 2007


Robert Fraser wrote:
> Walter Bright Wrote:
> 
>> Chris Nicholson-Sauls wrote:
>>> Or, as has happened to me a time or two, the programmer may not even 
>>> /know/ what's in the super class, if deriving from a class provided by a 
>>> library for example.  (This is particularly true with private fields, of 
>>> course.)
>> Exactly what problem does this solve? If you're writing a derived class, 
>> and you create another field of the same name as a field in the base 
>> class, what bug has been created? The base class functions will still 
>> use the base class field, the derived class functions will still use the 
>> derived class field. The fields aren't polymorphic, so no hijacking can 
>> happen.
>>
>> I just don't see the issue.
>>
> 
> I think the problem is with things like this:
> 
> class A
> {
>    string x;
>    string y;
> 
>    this()
>    {
>        x = "A.x";
>        y = "A.y";
>    }
> }
> 
> class B : A
> {
>    string x;
> 
>   this()
>    {
>        x = "B.x";
>    }
> }
> 
> public void main(string[] args)
> {
>    B b = new B();
>    A a = b; // a and b refer to the same object
>    writefln("A.x = %s", a.x);
>    writefln("B.x = %s", b.x);
>    writefln("A.y = %s", a.y);
>    writefln("B.y = %s", b.y);
> }
> 
> If A and B are maintained by different people, and the maintainer of B adds a new field "y", the main code can fail silently, which is, as you call it, "hijacking".

If methods were non-virtual by default I don't think there would be a 
case for this suggestion, but as it is, the idea kind of makes sense. 
Private methods are non-virtual by default (and cannot be made virtual), 
so it is even reasonable that this restriction should be enforced only 
for non-private member data.  This is really an extension of the 
"shadowing declarations are illegal" idea, which attempts to prevent 
maintenance-related mistakes from occurring.


Sean



More information about the Digitalmars-d mailing list