What should I learn?
Well, if you have covered the basics, you sure need some practice and guidance!
You could have a global function that:
- reads a block of text file,
- parses and creates the correct object dynamically (based on some condition), and
- returns a pointer to the object (cast to the base):
Account * parseOne(std::fstream& file); // Reference to opened file
Even if you just want the code, you will still have to go through an explanation. :)
Let us see it in a general sense.
Read a line
Very simply:
std::getline(file, line);
it. You should also check if the read was successful.
Parse it
You can do this as:
std::stringstream parse_me(line);
parse_me >> some_data_1;
parse_me >> some_data_2;
...
Create your object...
Here, you need to create it on the basis of currency_type
. Do:
if(currency_type == "GBP")
{
new_currency_object = new GBP(balance);
}
for each derived class.
...and The Code:
Putting it together:
Account * parseOne(std::fstream& file) // Reference to opened file
{
// To read a line from the file
std::string line;
// If the read failed, return NULL
if(!std::getline(file, line))
{
return 0;
}
// Read success
// Using stringstream so that different types of data can be parsed
std::stringstream line_buffer(line);
// Declare variables to be parsed
std::string currency_type;
float balance;
// Now parse it (note the order!)
line_buffer >> currency_type >> balance;
// Create a pointer to base...
Account * new_currency_object;
// ...and create the object based on the currency_type
if(currency_type == "USD")
{
new_currency_object = new USD(balance);
}
... for each currency
// We are done, return the fruits of our labour
return new_currency_object;
}
(Note that I assume you have a USD(float balance)
constructor. If not, set balance
yourself)
to be used as:
// open the file
std::fstream currency_file("my_currencies.txt");
// Read a currency
Account * a_currency;
// When the read finishes, we get NULL
while(a_currency = parseOne(currency_file))
{
// do something with a_currency. Maybe:
// list_of_currencies.push_back(a_currency) it?
}
Edit: And be sure to deallocate the memory once done! In fact, use of new
and raw pointers are not encouraged anymore. Thanks to this comment for suggesting it.
For further reading, see How to implement the factory method pattern in C++ correctly
.
Good luck!