Interface/abstract constructors
Steven Schveighoffer
schveiguy at yahoo.com
Mon May 16 13:47:32 PDT 2011
On Mon, 16 May 2011 16:34:20 -0400, nrgyzer <nrgyzer at gmail.com> wrote:
> == Auszug aus Steven Schveighoffer (schveiguy at yahoo.com)'s Artikel
>> If D supported runtime reflection (and it does to a very very small
>> degree), then you could use it to ensure the correct constructor is
>> available.
>> -Steve
>
> It's semicode, so I haven't try to implement it... it should only
> show what I'm trying to do.
> I'm currently thinking about an empty constructor in an abstract
> class like:
>
> abstract class ABC {
> this(Stream) {
> // do nothing
> }
> }
>
> class A : ABC {
>
> this(Stream s) {
> super(s);
> // read my block-specific bytes
> }
>
> }
First, this should work. Second, there is no good reason to do this. An
abstract class is allowed to have an empty constructor, but does not force
one to implement a Stream-accepting constructor.
For example, this would be a valid subclass:
class A : ABC {
this() { super(null); }
}
I'm not very good at explaining things sometimes, but if you think about
this for a while, it should sink in. Construction is a concrete activity,
you need to have all information about a class to construct it.
Interfaces and polymorphism is an abstract activity, you do not need to
have the full definition of the class to call virtual methods.
There is no point to have a constructor definition to force a signature,
because it just won't matter. The derived class does not have to override
base constructors because base constructors are not virtual methods.
What you probably want is a factory method such as:
ABC abcfactory(Stream s)
{
header = readHeader(s);
if(header == Aheader)
return new A(s);
...
else
throw new Exception("Unknown header");
}
What you should put in ABC is methods you would call on the objects
*after* they are constructed.
Now, with runtime reflection, you can "look up" classes based on the class
names and their appropriate constructors. I've written such systems in
C#, and it's not extremely easy to do it safely. It's much more
straightforward and less error prone to just use a factory method like the
above.
-Steve
More information about the Digitalmars-d-learn
mailing list