Functions from BankAccount

Before you can read objects from a file with more than one type of objects your file must be created in an appropriate way. In the case of the accounts, when an item writes itself, the first thing it writes is its type.

void SavingsAccount::write(ostream &out )
{
	out << Account::SAVINGS << endl; // write out the type of item
	out << _acctNumber << endl;
	out << _balance;
}
void CheckingAccount::write(ostream & out )
{
	out << Account::CHECKING << endl; // write out the type of item
	out << _acctNumber << endl;
	out << _balance;
}

The function that writes to the array uses an iterator and calls on each item to write itself.

void AccountArray::write()
{
	ofstream out("Accounts.dat");
	ArrayIterator < AcctPtr > next(accts); //Create the iterator
	out << accts.numberInArray() << endl; //write the number of items to the file
	while (next) // loop until the last item in the list
	{
		next()->write(out);  //let the item send itself to the file
      		out << endl; // each object begins on a new line
		next++; // get the next item in the list
	}
}

Once a file has been created in this format, it is easy to read the file using the create function to clone the appropriate type of object.

void AccountArray::read()
{
	ifstream in("Accounts.dat");
	int size;
	in>>size; //first thing in file is the number of items
	Account* types[]={&SavingsAccount(),&CheckingAccount()}; // The list of object types
	for (int i = 0;i < size;i++)
	{
		int whichType;
		in >> whichType; // This is the subscript of the type listed above
		AcctPtr nextOne = Account::create(types[whichType]); // actually create the object
		nextOne->read(in); // let it read itself
		accts.insertItem(nextOne); // Insert it in the array
	}
}

To get the whole project click here.