简体   繁体   中英

C++ Issue with Polymorphism - Data overwritten

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 , Motorcycle and Lorry instance for each new entry, since now you reuse the exiting instances and in that way rewrite data. You should do:

if(selection=="Car")
{
   vehicletwod[arrayCounter] = new Car();
   vehicletwod[arrayCounter]->setName(theName);
   vehicletwod[arrayCounter]->setYear(theYear);
}

if(selection=="Lorry")
{
   vehicletwod[arrayCounter] = new Lorry();
   vehicletwod[arrayCounter]->setName(theName);
   vehicletwod[arrayCounter]->setYear(theYear);
}

if(selection=="Motorcycle")
{
   vehicletwod[arrayCounter] = new Motorcycle();
   vehicletwod[arrayCounter]->setName(theName);
   vehicletwod[arrayCounter]->setYear(theYear);
}

Each time you choose a new vehicle, you must create a brand new object to hold it. Replace your line:

vehicletwod[arrayCounter] = myCar;

with:

vehicletwod[arrayCounter] = new Car;

And likewise for the other types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM