I got this example
Parent class Vehicle
Child Classes Car, Motorcycle, & Lorry
This is what happens: In main.cpp I create
VehicleTwoD *vehicletwod[100];
Car *myCar = new Car();
Motorcycle *myMotorcycle = new motorCycle();
Lorry *myLorry = new Lorry();
This is what I do:
if(selection=="Car")
{
vehicletwod[arrayCounter] = myCar;
vehicletwod[arrayCounter]->setName(theName);
vehicletwod[arrayCounter]->setYear(theYear);
}
if(selection=="Lorry")
{
vehicletwod[arrayCounter] = myLorry;
vehicletwod[arrayCounter]->setName(theName);
vehicletwod[arrayCounter]->setYear(theYear);
}
if(selection=="Motorcycle")
{
vehicletwod[arrayCounter] = myMotorcycle ;
vehicletwod[arrayCounter]->setName(theName);
vehicletwod[arrayCounter]->setYear(theYear);
}
cout << "Record successfully stored. Going back to the main menu " << endl;
The issue here in main.cpp is some kind of switch-case menu with a prompt, so if the user chooses to insert a new vehicle, he selects the vehicle type, and will manually input some value like theName and theYear. Then it will be set to the vehicletwod[arrayCounter].
The program runs into an issue when there is more than 1 object of the same child type in the list of vehicletwod.
If the user does something like
Car
Motorcycle
Car
The 1st car value will be overwritten by the latest Car (the 2nd car)
However, if they input
Car
Motorcycle
Lorry
Itis fine because each object only runs once.
How do I change my declaration so it will not overwrite the data of the previous same child class.
You need to create a new
Car,MotorcycleandLorryinstance for each new entry, since now you reuse the exiting instances and in that way rewrite data. You should do: