Question

If I'm writing classes derived from a parent class to file, how do I determine which class I am reading in from file?

Basically I have 3 derived classes: DerivedA, DerivedB, DerivedC. When writing to the file I have done this:

DerivedA
   attribute1
   attribute2
   attribute9
DerivedB
   attribute5
   attribute6
DerivedC
   attribute4
   attribute7

How do I set my if statements up to determine which class I am reading in at the moment?

EDIT:

I am building a list of homes with specific different attributes to each home.

list<Homes*> home;
Homes *tmp;
while(ins>>tmp)
{//determine which home it is
  tmp=new ***//depends on which derived class it is;
}

In my data file it will say:

Brickhome
solar panels
3 bathrooms
Spiral Staircase
LogCabin
gravel driveway
fireplace
Castle
10 butlers
1 moat

I need a way of determining which home needs to be created.

Was it helpful?

Solution

You can't know which derived type to construct before you read the line that names it. What you can do is have a function that reads the first line, then delegates the rest to the appropriate subclass constructor.

list<Homes*> home;
string str;
while(ins >> str)
{
  switch(str)
  {
    Homes *tmp;

    case "Brickhome":
      tmp = new Brickhome(ins);
      break;
    case "LogCabin":
      tmp = new LogCabin(ins);
      break;
    case "Castle":
      tmp = new Castle(ins);
      break;
    default:
      throw("unknown type of home");
  }
  home.push_back(tmp);
}

Note that the subclasses must have a sensible way of knowing when to stop (e.g. Brickhome must either know how many attributes it has, or know that "LogCabin" cannot be one of its attributes, and must therefore be put back into the stream before the constructor terminates).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top