I am writing an class, which is going to be subclassed many times. The
superclass will have several methods, which I want to return new instances
of the class. However, when the instance of the class is a subclass, I want
the references to be of the subclass type.
For example:
Class1 has a method GetNextObject() which returns a new object of type
Class1.
Class2 is a subclass of class1
When I call class2.GetNextObject(), I want the instance returned to be of
type class2 (with the appropriate constructor having been called), without
having to override the GetNextObject method.
Since class2 is a subclass, the two are type-compatible, so syntactically
and semantically everything is fine. However, I can't find a way of
instantiating a new object of the same subclass as the current object, from
code within the superclass. What I really want is to be able to say
NewObject=new me.type
Within the superclass function, to create a new object of whatever type the
reference actually is.
I can think of a workaround, which uses a virtual method NewObject(), which
returns a new instance, which is overridden in each subclass to instantiate
a member of that subclass. This would work fine except for the following
issues:
1) The I am not the only person who will be subclassing this class. If I
make the class dependent on having an overridden method and somebody else
fails to override it, it could cause problems in the application. I also
can't think offhand of a way of flagging whether or not the method has been
overridden, to generate meaningful errors if this were the case.
2) This is a messy and inelegant way of doing it and I don't like writing
messy and inelegant code.
Does anyone know of a better way of doing this?
Apologies for the rather convoluted explanation.
Steve
|