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

James Dennett jdennett at acm.org
Mon Aug 13 21:04:38 PDT 2007


Walter Bright wrote:
> Robert Fraser wrote:
>> 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".
> 
> 
> It's not hijacking at all, it's overriding. a.y does not change, i.e. it
> is not hijacked by adding a definition to B. Only b.y changes, and
> that's unsurprising.

Not to one surprised by code in B that used to refer to A.x
and now doesn't.  It's a well-known problem, and C++ compilers
mostly include at least an option to warn about it, as users
find that helpful.

Certainly, sufficient care when making changes can avoid this
problem, but then "sufficient care" can avoid all bugs; tools
should help.

-- James



More information about the Digitalmars-d mailing list