Constructor inheritance & polish function

Kristian kjkilpi at gmail.com
Mon Aug 21 10:05:28 PDT 2006


I forgot to mention that this would not break the old code.

I can't think any reason why this is not implemented in D (or in C++).  
Maybe someone could enlighten me on this? Surely it'll make subclassing  
easier and more bug free. The overload function hiding rule does not apply  
here. That is, changing the constructors of Base won't break the  
constructors of Derived (because they just call the ones of Base).

If someone would prefer a (little) better example, here's a one:

class Button {
     this(...) {...}
     this(...) {...}
     //and zillion other constructors...

     void paint() {...}  //paints the button on the screen
}

Now we'll need a button that paints a cross over the button in some  
situations:

class MyButton : Button {
     void paint() {
         super.paint();

         if(m_is_crossed) {
             //paint the cross
             ...
         }
     }

     bool m_is_crossed = false;
}

No need to rewrite (copy&paste + modify) those zillion constructors of  
Button.

If a more complex initialization should be done (i.e. in addition of "bool  
m_is_crossed = false;"), then the polish function would be candy.


On Mon, 21 Aug 2006 10:39:31 +0300, Kristian <kjkilpi at gmail.com> wrote:
> Let there be classes Base and Derived. Base is the base class of Derived.
[snip]
>
> class Base {
>       this() {...}
>       this(int val) {...}
>
>       void f() {...}
> }
>
> class Derived : Base {
>       void f() {...}  //overrule a member function
> }
>
> void func() {
>       Derived obj = new Derived(1);  //calls 'Base.this(int)' (now a  
> compile
> time error)
> }
>
[snip]
> class Derived : Base {
>       this_polish() {  //is called after a constructor
>           f();
>           }
> }
>
> void func() {
>       Derived obj = new Derived(1);  //'obj.m_val' == 100 (first 1, then  
> 100)
> }
>
>
> This would reduce redundant code, which is a possible source for typos  
> and
> errors. It would also be easier to maintain: if parameter lists of Base's
> constructors are modified, no changes will be required for Derived.



More information about the Digitalmars-d mailing list