I have a parent class with several subclasses and was going to add a function that generated and returned a pointer to one of the subclasses randomly. Eg.,
class Parent { ... }
class Child1 : public Parent {...}
class Child2 : public Parent {...}
...
class ChildN : public Parent {...}
// returns one of the children, randomly
Parent* generate_random();
On one hand, I could write generate_random
hardcoding the number of Child classes and updating this number each time I add a new subclass of Parent or remove an old one. But this seems a bit fragile. Similarly, I could even use a const variable to keep track of the number of child classes. Again, I'd have to update this manually whenever adding and removing classes. This also seems fragile.
In contrast, in a language like Python, I might put a decorator above the declaration of each subclass of Parent, that would increment a count of all child classes and use that. For instance:
_num_subclasses = 0
def _register_subclass(cls):
global _num_subclasses
_num_subclasses += 1
class Parent(object):
...
@_register_subclass
class Child1 (Parent):
...
@_register_subclass
class Child2 (Parent):
...
...
Is there a way to do something similar using the preprocessor? Or is there a way to run a method once and only once before or after a class declaration? (It would be great to get to the point where I could not only increment a counter for each class, but also register a factory for it in a singleton map.) Or, more generally, how do others deal with this type of issue? Please let me know if something in my question was unclear or needs to be rephrased.