News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ Tips:IO - Using switches in IO routines

Started by ben2ong2, October 06, 2006, 11:12:40 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

PROBLEM: You are not allowed to view links. Register or Login (Brian Hook)

You have just described one of the fundamental problems with implementing
persistent objects.  Basically, you DO have to read in the identifier and
write it out, and you will need a "core" routine somewhere responsible for
"Switching" on this identifier.

BaseObject *ReadObject( FILE *fp )
{
int type;
BaseObject *thingy;

   fread( &type, sizeof( type ), 1,  fp );
   switch ( type ) {
      case Type1:
         thingy = new Type1;
         thingy->ReadFromDisk( fp );
      . . .
   }
   return thingy;
}

Obviously the above doesn't do error checking, and you may want to use
exceptions, iostreams, etc.

If there are better methods, I'd love to hear about them.


RESPONSE: p j l @graceland.att.com (Paul J. Lucas), AT&T

The sexiest method I've used is to have each derived class
populate a global Map<String,Base*> mapping the class's name to
a pointer to a token instance.  This can be done by having each
class have a static data member of itself that uses a special
constructor to put the class's name and a pointer to it into
the global Map. 

The global Map can actually be a protected static data member of
Base.  The write functions would prefix their data by their
class's name; the Base::read function would read the class's
name and, using the Map, get access to a token instance of an
object of the right derived type.  Base would have a virtual
member function called clone.  This would be called on the token
object to clone itself.

This method uses no switch statements and is immune to adding or
deleting a derived class.  I think it's extremely elegant.

The only obvious gotcha is what to do with reading an old file
that has data for a derived class that no longer exists.  But,
that's a problem no matter what you do.  The easiest solution is
to skip it (assuming, in addition to writing a class's name, you
also wrote some sort of "end" marker or used a byte count so
you'd know when to stop skipping).
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login