super constructors: I can't take it anymore!
Regan Heath
regan at netwin.co.nz
Wed Aug 16 18:05:25 PDT 2006
On Wed, 16 Aug 2006 16:43:16 +0300, Serg Kovrov <kovrov at no.spam> wrote:
> * Regan Heath:
>> import std.stdio;
>> typedef int function(int i) WNDPROC;
>> class BaseWindow
>> {
>> void register(char[] cname) { writefln("register(",cname,")"); }
>> void create(int function(int) f) { writefln("create(",f(1),")"); }
>> char[] classname() { return "BaseWindow"; }
>> WNDPROC windproc() { return cast(WNDPROC)function int(int i){return
>> i;}; }
>> this() { register(classname()); create(windproc()); }
>> }
>> class FrameWindow : BaseWindow
>> {
>> override char[] classname() { return "FrameWindow"; }
>> override WNDPROC windproc() { return cast(WNDPROC)function int(int
>> i){return i*2;}; }
>> }
>> void main()
>> {
>> FrameWindow b = new FrameWindow();
>> BaseWindow a = new BaseWindow();
>> }
>
> Thank you, Regan.
>
> This is pretty good looking solution. Seems all solutions are about to
> avoid using constructors in subclasses at all.
Or rather you should avoid trying to 'remove' initialisation behaviour
from a base class, and instead place optional initialisation in seperate
methods which can be overridden.
Constructors are not like ordinary methods, they're always inherited and
can only be overridden/removed by going to extremes. This is a much better
situation than the alternative which allows you to easily 'forget' to
initialise you base class, IMO.
> Sadly, constructors appears to be weak in D. I wish some day it will be
> changed.
Actually, I disagree. I think the D behaviour is safer and more useful
than the alternative. Especially given the fact that it can still
handle/solve the problem you had, and does it in a more elegant fashion
(IMO) than you were initially going to use, i.e. adding the same lines
(with slightly different data) to every sub class constructor (something
you might have forgotten to do at some stage)
Regan
More information about the Digitalmars-d-learn
mailing list