Hello, I have been trying multiple things and thinking for a while, but I just can't think of the correct syntax/logic for it.
I have a base class and two derived classes. I am using dynamic binding to make a vector which stores instances of all 3 classes. Then, I am reading in from a file, it specifies which class it belongs to (I will use an if statement to check the string in the file, e.g. "base", "der1", "der2"). It will then push that onto the stack.
I can manage the above if there is only one of each class, however, there are multiples of each one. Therefore, something like the below code wont work:
vector<Base*> myVec;
1 2 3 4 5 6 7 8 9
|
Base *b = new Base;
Der1 *d1 = new Der1;
Der2 *d2 = new Der2;
//read the file and fill in the classes data members
myVec.push_back(b);
myVec.push_back(d1);
myVec.push_back(d2);
|
The above will just read each type of class once each and push them on. How would I implement something along the lines of:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
for(int i = 0; i < lines; i++) //lines = how many lines in file
{
cin.get(whatType, ':'); //reads a string up to the delim char :
if(whatType == "Base")
{
//read line and fill rest of data members...
myVec.push_back(b);
}
else if(whatType == "Der1")
{
//read line and fill rest of data members...
myVec.push_back(d1);
}
if(whatType == "Der2")
{
//read line and fill rest of data members...
myVec.push_back(d2);
}
}
|
However, when the same class type is read in again, the previous one will be overwritten as well as it's a pointer to one instance? So outputting at the end will be incorrect. I want them all to be unique instances.
How would I go about doing that? I have no clue.