If I have a class called "A" and I have two classes that derive from it lets say "B" and "C" how do I create a new instance of both B and C not knowing which is which. This probably sounds confusing so let me clarify and use similar code as mine.
Base class:
class A {
stuff...
}
Derived classes:
class B : A{
stuff...
}
class C : A {
stuff...
}
Then in some other class I have:
class Z {
void Derp() {
foreach(A classA in listOfA's) {
create new instance of derived class
}
}
}
I simply cannot just say B = new B()
and C = new C()
because maybe B isn't in the list at all or maybe there are three B's and one A in the list. Surly there is some way to do it but if not I could have a switch-case statement like:
class Z {
void Derp() {
foreach(A classA in listOfA's) {
switch(classA) {
case is B:
B = new B();
break;
case is C:
C = new C();
break;
}
}
}
}
}
I would like to avoid doing it this way unless necessary because every time I create a new class that derives from class A I'll have to remember to add another case statement in there.
So how should I do this?
Thanks.
A common C++ solution to this is the so-called virtual constructor idiom: you define a virtual function called clone
in the base class A
, and then override it in B
to return a new instance of B
and in C
to return a new instance of C
.
If you need a blank instance instead of a clone, you could add a newInstance
function that uses the default constructor.