How to populate objects of derived class with data members into a pointer array of base class

0

When i try to output a material of type string of class 'Brakes' using polymorphism, it doesn't print correctly. I believe the problem has to do with me instantiating a new derived object. How do I populate a derived object with data members into an array of pointers of the base class in C++? Sorry if the format for the code is wrong rr if I didn't give enough information, it is my first time here.

in main():

Parts *partsList = new Parts[arrayCount];

function call:

populateArrayBrakes(&partsList,tokens,element);

function to populate the array with data:

void populateArrayBrakes(Parts *partsList[], string tokens[], int element){
        partsList[element] = new Brakes(tokens[1],tokens[2]...);
}

but for some reason when I output using polymorphism, there are spaces in the output and the materials are wrong (the first material is supposed to be "Synthetic Blend"):

brakes material: 1 Organic
brakes material: 2 Organic
brakes material: 3 Organic
brakes material: 4 Ceramic
brakes material: 5 Ceramic
brakes material: 6 Ceramic
brakes material: 7 Ceramic
brakes material: 8 Ceramic
brakes material: 9
brakes material: 10 Ceramic
brakes material: 11 Carbon Metallic
brakes material: 12
Process returned -1073741819 (0xC0000005)   execution time : 1.425 s
Press any key to continue.
c++
arrays
polymorphism
asked on Stack Overflow May 13, 2020 by changemajornow

1 Answer

0

partsList in main is a pointer to an array of Parts.

populateArrayBrakes populates an array of Parts * (pointers to parts).

Your use of &parts will results in Undefined Behavior because any access in populateArrayBrakes of parts[element] where element is not 0 will be out of bounds.

What you want is to declare partsList as a pointer array,

Parts **partsList = new Parts *[arrayCount];

However, use of raw pointers should be avoided and you should be using std::vector and smart pointers.

answered on Stack Overflow May 13, 2020 by 1201ProgramAlarm

User contributions licensed under CC BY-SA 3.0