Hijacking

Reiner Pope some at address.com
Wed Aug 8 00:04:42 PDT 2007


Bill Baxter wrote:
> Walter Bright wrote:
>> kris wrote:
>>> There's a related problem where a public method is added to a 
>>> base-class A (as in your example) but where the signature is 
>>> *exactly* that of one existing in derived class B. If A actually 
>>> calls that new method internally, "bad things"tm will almost 
>>> certainly happen, since B never intended to effectively override the 
>>> newly-added method in A.
>>>
>>> This is a very hard problem to isolate yet can be easily remedied by 
>>> the compiler. The request was first made two or three years back, and 
>>> once or twice since then: you make the "override" keyword *required*.
>>>
>>> When "override" is required, the compiler can easily trap this 
>>> related type of hijacking and avoid such nasty surprises.
>>
>> That is a good point. The reason I haven't added it is because I'm not 
>> sure how annoying it will be to have to always add the 'override' 
>> keyword. It might be one of those things like exception specifications 
>> where everyone says it's a good idea but guiltily hate in secret <g>.
>>
>> Mitigating factors are private and final methods cannot be overridden.
> 
> Although, I generally like the idea, I fear that requiring 'override' 
> will have side effects for mixins.  The writer of the mixin has no way 
> of knowing if the methods will override something or not.
> 
> I'm thinking the only reasonable solution would be to allow mixins to go 
> on as they currently are, without enforcing the use of 'override'. 
> However, an accidental override that comes in via a mixin seems like a 
> very likely source of subtle bugs.  And requiring a special exception to 
> the rules is not really desirable in the first place.
> 
> --bb

Interesting point. I think, however, that an explicit solution which 
re-enables using mixins as overriding functions is the best solution (as 
you point out, the alternative is subtle bugs). Perhaps a new form of 
alias, to add the override?

template Foo()
{
     int foo() { return x*x; }
}

class Base
{
     int foo() { return 5; }
}

class Derived : Base
{
     int x = 5;

     mixin Foo my_foo;

     // specify that my_foo.foo overrides Base.foo
     alias my_foo.foo Base.foo;

     // or specify that my_foo.foo is an override
     alias my_foo.foo override foo;

     // (but obviously not both at once)
}

   -- Reiner

PS. Notice how I've (not-so-)subtly worked in my suggestion from 
http://www.digitalmars.com/d/archives/digitalmars/D/Implementing_required_methods_with_alias_56011.html 
;-)



More information about the Digitalmars-d mailing list