I have these C++ classes defined as follows:
class A
{
public:
B *createB();
};
class B
{
public:
virtual void fun() = 0;
};
class B1 : B {/* ... */};
class B2 : B {/* ... */};
So basically B is an abstract class, B1 and B2 are concrete implementations of B, and A creates an instance of type B somewhere in its code. It's important to note that A is not a factory, A::createB
is just an example.
I'd like to be able to pass a subclass of B during initialization of A so it is possible to create instances of the former by the latter as necessary during runtime. Example:
A *a1 = /* sorcery here */;
A *a2 = /* another magic code */;
a1->createB(); // getting B1
a2->createB(); // getting B2
What is the best way to achieve it? Is it possible without using templates?
Basing on responses I ended up with this. Thanks!
class B
{
public:
virtual void fun() = 0;
virtual B *clone() = 0;
};
class B1 : public B
{
public:
virtual void fun()
{
std::cout << "B1" << std::endl;
}
virtual B *clone()
{
return new B1();
}
};
class B2 : public B {/* analogous to B1 */};
class A
{
public:
A(B *b) : b(b) {};
B *createB()
{
return b->clone();
}
private:
B *b;
};
A(new B1()).createB()->fun(); // prints "B1"
A(new B2()).createB()->fun(); // prints "B2"