Reputation: 4886
Say you have an abstract base class:
abstract class abstractBaseClass {
public abstractBaseClass(object argument);
public abstractBaseClass instanceMethod() {
//call the constructor of the concrete class here.
}
}
And you have a base class:
class baseClass {
public baseClass(object argument) : abstractBaseClass(object argument)
}
If you have an instance method on abstractBaseClass
is there any way to call the constructor of that concrete class inside the instance method without resorting to reflection?
It seems to be reasonable to assume there is at least one constructor with the signature concreteBaseClass(object)
on any given concrete base class.
Upvotes: 0
Views: 224
Reputation: 62276
If you have an instance method on abstractBaseClass is there any way to call the constructor of that concrete class
You already do that, actually. Abstract
class can not be initialized if not by it's derivates.
abstractBaseClass abs = new baseClass();
The real object type here is baseClass
, so the ctor
of it will be called by convention.
EDIT
if you mean construct *a new * real object that is hosted inside abstract reference (something that is mantioned by Sevy in comments), I would suggest, at this point, just use override pattern. Something like this:
abstract class abstractBaseClass {
public abstract abstractBaseClass(object argument);
public abstract abstractBaseClass CreateMe();
}
class baseClass : abstractBaseClass
{
...
public override abstractBaseClass CreateMe(){
return new baseClass();
}
}
after use it like
abstractBaseClass newAbs = abs.CreateMe();
Something like this, just an idea. You should figure out by yourself the real, concrete implementation that fits your needs.
Upvotes: 3
Reputation: 5187
If you mean, "can I just call new baseClass()
inside of abstractBaseClass
, then yes, you can.
If you mean "can I dynamically figure out what class inherits from me and new one up", then no, not without using reflection. You have no way of knowing if there are more than one types inheriting from you.
This is, by the way, a pretty weird scenario and sounds like it violates a whole lot of best practices for OOP. Perhaps you would be better off creating a factory class to create your objects?
Upvotes: 0