Inheritance and in-contracts

Joseph Rushton Wakeling via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 5 14:39:38 PST 2014


Suppose I have a base class where one of the methods has an in-contract, and a 
derived class that overrides it:

/////////////////////////////////////////
import std.stdio;

abstract class Base
{
     abstract void foo(int n)
     in
     {
         assert(n > 5);
     }
     body
     {
         assert(false, "Shouldn't get here");
     }
}

class Deriv : Base
{
     override void foo(int n)
     {
         writeln("n = ", n);
     }
}


void main()
{
     Base b = new Deriv;

     b.foo(7);
     b.foo(3);
}
/////////////////////////////////////////

This outputs,

n = 7
n = 3

In other words, the lack of explicit in-contract on Deriv.foo is being taken as 
an _empty_ in-contract, which is being interpreted as per the rule that a 
derived class can have a less restrictive contract than its base (cf. TDPL 
pp.329-331).

Question: is there any way of indicating that Deriv.foo should inherit the 
in-contract from the base method, without actually calling super.foo ... ?

Following the example on p.331, I did try calling super.__in_contract_format(n) 
(... or this.Base.__in_contract_format(n) or other variants), but that doesn't 
seem to work:

     Error: no property '__in_contract_foo' for type 'incontract.Base'

... so can anyone advise if there is a reasonable way of achieving this?

Thanks,

      -- Joe


More information about the Digitalmars-d-learn mailing list