C++ - unknown array size, unknown object type. Help!
Archive - Originally posted on "The Horse's Mouth" - 2011-04-17 12:00:59 - Graham Ellis
• I don't know how many records / object I'm going to read from a data file into an array - so I can't set the size of my array
• I don't know what sort of object I'll be creating from a line I've read from a data file until I analyse it, so I can't call the constructor directly.
You could write a program to read take up to a certain maximum number of records / objects, but one day you'll find that someone want to run that program with more records than you've allowed for. The solution (C++ answer / term) is to use a vector - which is line an array or objects in many ways, but can dynamically expand. It saves you writing you own code with realloc calls.
And you could write a program which analyses incoming data lines before calling the appropriate constructor - but by doing so you're moving code which really should be in the class into each application. The solution is to provide a static method in the base class of all possible objects, which analyses the data and decides which constructor to call. Such a method is known as a factory method.
An example showing these techniques - from the C++ course I ran the week before last - is [here]. It also shows some file and string handling - a little bit of everything as I pulled together elements of the C++ language into a very straightforward application, but one covering many aspects.
I might not know how big my array should be, or what type of data each line will contain - but I do know that our next series of C and C++ courses starts at the very end of May - see [here]. If you've missed those, there are further courses in August, and in the autumn - use the same link as we'll update our page.