Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ polymorphic load/save

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.

like image 429
Roddy Avatar asked Dec 16 '22 19:12

Roddy


1 Answers

That's about the best you could do, you might clean it up a bit though by wrapping the if in a factory class.

like image 156
Luchian Grigore Avatar answered Dec 27 '22 09:12

Luchian Grigore