[comp.lang.c++] Class derivation and disk files

saito@sdr.slb.com (Naoki Saito) (12/02/89)

	I have a question about the treatment of the disk files and its
class representation.

Suppose you have classes D1, D2, ..., Dn.  All of D* share some common data
structures and each D* has additional data structructure.  There exit
corresponding files on the disk.  The class B is designed to share the
commonality among D* classes.  Each class has a method called "read" and
"write" to do I/O with disc files.
As far as the user of these classes wants to write the class specific tasks,
there's no problem.  However, when he/she wants to do some processing on the
common data part can be represented by B, he/she has to face the difficulty:
when he/she specifies the filename to read, the program also has to know which
"read" method should be used.

I thought the following two cases:

(1) The brute force approach.  The class designer prepares the function
"resolve" to classify the data file.  In this case, the user's program looks
like

main()
{
  B* base;
  resolve(B, filename);
  B->read(filename);  // This actually calls one of D* read methods.
// ... do something here.
  B->write(filename2);
}

And the functon "resolve" looks like

int resolve(B*&, const char*)
{
int class_type = check_header(filename);
switch (class_type)
 {
   case '1': B = new D1, break;
   case '2': B = new D2, break;
   case '3': B = new D3, break;
	.
	.
	.
 }
}

However, this is a little bit awkward.  What I want to say is the OOP gives you
some kind of generic functions such as "read" as above(in C++ these are called
"virtual" functions), someone has to prepare a kind of switch statement
somewhere in the code.

(2) The class specifier approach.  The class designer puts the protected member
called "int whichD" in the class B which shows which D class type this B
instance actually represents.  Then, in the read method in the class B, the
"check_header" function is called first, and puts the class number to "whichD",
and then invokes the corresponding read method for that class.
However, I'm not sure that whether "this" pointer in the read method of the
class B can be dynamically changed to pointer to its derived instances or not.

Is there any way to avoid switch statement completely in the above example?
Or rather than eliminating the switch statement, the class designer should
provides the function "resolve" to the user?  Or should I restructure the
class hierarchy?


Thanks in advance,
-- 
Naoki Saito (saito@sdr.slb.com)
Schlumberger-Doll Research