I assume that all possible subclasses are known in your getRandomObject
function, and you want to create a new instance on every call. Then this is a viable solution:
A *getRandomObject() {
int r = getRandomIntInRange(0, 3); // Some method returning a random int from [0,1,2]
switch (r) {
case 0: return new B1();
case 1: return new B2();
case 2: return new B3();
default: return NULL; // should never come here...
}
UPDATE:
If your method might not know all possible subclasses, a registration mechanism might be possible, where you store functionoids that return new instances (factories).
A quick outline:
// Somewhere in your code
A *b1Factory() { return new B1(); }
A *b2Factory() { return new B2(); }
A *b3Factory() { return new B3(); }
// somewhere you have a factory list
typedef A* (*aSubclassFactoryFunc) (void);
std::vector<aSubclassFactoryFunc> factories;
A *getRandomObject() {
int r = getRandomIntInRange(0, factories.size()); // Some method returning a random int from [0,1,2,...,factories.size()]
return factories[r](); // Call random factory
}
New subclasses simply must add a factory method to the factory list.
UPDATE 2:
A registration mechanism could be done like this:
#define REGISTER_A(B) \
struct b_subclass_register_##B {\
b_subclass_register_##B() {\
registerASubclass(b_subclass_register_##B::create);\
}\
static A *create() { return new B; }\
} dummy_instance_##B;
This is a makro that creates a struct and creates a dummy instance in global scope. In its constructor, the subclass is registered.
You use this in your subclasses CPP files, like:
REGISTER_A(B1);