Let's say there is a base class
class Base
{
}
and the user has created a new subclass
class NewDerivedClass : public Base
{
}
There is also a enum for all the subclasses:
enum SubclassId
{
Derived1_Id,
Derived2_Id,
...
NewDerivedClass_Id // User has to add this line
}
Now, there is also a factory which creates derived instances based on the SubclassId
:
class SubclassFactory
{
Base* CreateSubclassInstance(SubclassId subclassId)
{
switch(subclassId)
{
case SubclassId::Derived1_Id:
return new Derived1(params);
case SubclassId::Derived2_Id:
return new Derived2(params);
...
// User has to add the following lines:
case SubclassId::NewDerivedClass_Id:
return new NewDerivedClass(params);
}
}
}
- How can I force the user of my
Base
class to add newId
in enum? - How can I force the user of my
Base
class to create it's instance inSubclassFactory
?
In the best case I would like to see a compile-time error. Unit test solution to this problem is also acceptable.
Additional information.
1. Users of the Base
class create new subclasses in the client side.
2. My code operates in the backend. I get the subclass id remotely and use Factory
to make instances of the subclasses created by client programmers.