i have a question about the best way to solve this problem i have with determining what class to pass to my overloaded operator<<() function..
my << function reads a line from the input file, tokenises it and inserts that data into either a Customer, Tour or GuidedTour object, depending on the first token for that particular line
Tour is the base class of GuidedTour, but Customer is not related at all, so i dont think i can use a cast between them (or can i?)
here is the code:
for (unsigned int i = 0; i < inputFiles.size(); i++)
{
ifstream fin(inputFiles[i], ios_base::in);
int line = 0;
char c;
while (fin)
{ line++;
c = fin.peek(); //use peek() to check first char of next line
if (c == ios::traits_type::eof())
break;
// this is where i am having the trouble
else if (c == 'C')
Customer *temp = new Customer();
else if (c == 'g')
GuidedTour *temp = new GuidedTour();
else if (c == 't')
Tour *temp = new Tour();
else
throw boost::bad_lexical_cast();
try
{
fin >> *temp;
}
catch(boost::bad_lexical_cast&)
{
cerr << "Bad data found at line " << line
<< " in file "<< inputFile[i] << endl;
}
customers.push_back(temp);
}
fin.close();
}
its obvious where i am having the trouble; because i am initialising the objects inside the conditional blocks, they wont persist after that block is finished, but i have no idea how to make them persist.. or is it just not possible to do what i am trying to achieve?
i understand this is not a very direct question, i've just been bashing my head against a brick wall trying to solve this problem for ages, so any advice would be greatly appreciated..
EDIT: is it possible to do something like use a void pointer at the start of the loop called temp, and then cast it to an object within the conditionals before passing it to fin << *temp?