I'm saving and reloading a bunch of different objects all derived from a common base to a file, and obviously I need to store the class name (or something similar) in order to create the correct object type on reloading.
Saving is easy:
class Base
{
virtual string className() const = 0;
void saveToFile()
{
write(className());
... other writing stuff
}
}
class Derived1: public Base
{
string className() const { return "Derived1"; };
...
}
class Derived2: public Base
{
string className() const { return "Derived2"; };
...
}
and, loading is easy if you don't mind duplicating the strings...
static Base * Base::factory(const String &cname)
{
if (cname == "Derived1")
return new Derived1;
else if (cname == "Derived2")
return = new Derived2;
else ...
}
void load()
{
String cname = readString();
Base * obj(Base::factory(cname);
obj->readIt();
}
But, the duplicated strings offends my sense of DRY: Ideally, className()
could be static virtual
but that isn't allowed. I have a feeling that I'm missing an obvious 'clean' way round this, but I can't see it yet. Any suggestions?
Note: OK, code slightly tweaked using a factory method. Note that this doesn't actually answer the problem!
Note #2: The code above isn't trying to be a perfect representation of the ultimate factory pattern. I'm not concerned with unwanted linkage between base and derived classes, or potential difficulties in extending the hierarchy. I'm looking for answers that will simplify the code rather than complicate it.
That's about the best you could do, you might clean it up a bit though by wrapping the if
in a factory class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With