Hi.
I have two classes, one of which is a subclass of another, and differs only by the fact that it contains an additional member variable to its parent. I am not using the default constructor, passing in a reference to a single object as the constructors parameter. What I would like is for the constructor of the parent to examine this object, and then determine whether to construct an instance of the parent class (in most cases) or the subclass (in a few specialised cases).
class Superclass
{
public:
Foo foo;
Superclass(MyObject* object)
{
foo = object->GetFoo();
if(object->CreateSubclass())
{
//Create Subclass
}
else
{
//Create Superclass
}
}
};
class Subclass : public Superclass
{
public:
Barr barr;
Subclass(MyObject* object)
{
barr = object->GetBarr();
}
};
I'm aware of the factory design pattern, but don't want to have to have a factory object just for this. I'd rather duplicate the Superclass initialisation stuff into the Subclass (which seems bad) and then examine the object at each of the points where a Superclass is created and then call the appropriate constructor:
Superclass* class;
if(object->CreateSubclass())
{
class = new Subclass(obj);
}
else
{
class = new Superclass(obj);
}
Is this sort of thing possible, and if so how would I go about calling the subclasses constructor from Superclass constructor? I've tried making a call to Subclass(object)
, but I run into issues with both Superclass and Subclass needing to be defined before the other.
Thanks for any advice you can provide.