Reputation: 837
Regarding: Child Class in a Array C++
Hi guys, sorry as i am stuck on some work.
Basically this is what happen
I have a parent class call vehicle and it got 2 child class call
Car and Motorcycle
Parent class have the following value:
string Name: value either Car or MotorCycle
wheels : 4 or 2 (depends is car or motorcycle)
Notes On Wheel:
wheel[0] : Fine condition
wheel[1] : need some repair
wheel[2] : Fine condition
wheel[3] : Fine condition
I wonder how do i record this all in VehicleTwoD Array
Car / Motorcycle is a child class of Vehicle, what do you guys suggest. I try to create an object of VehicleTwoD vehtwod[100];
then i do a for loop to prompt. but how do i record the object car / motorcycle into my VehicleTwoD array and how do i record the string array inside too. so every VehicelTwoD array element contains the information
Name ( Motorcycle or Car)
Wheel ( depend on name - 2 or 4)
String array - notes size depend on what is choosen
How do i record all in 1 array.
Thank you very much , i know this is polymorphic and i know this is OOP and i know i need study more. but i really stuck on this part on creating such array that can hold other array.
THANKS!
Upvotes: 0
Views: 232
Reputation: 101456
Simplifying solution by not addressing irrelevant dimensionality of the storage array.
Create an array of Vehicle
pointers, and store those:
vector<unique_ptr<Vehicle>> vehicles_;
vehicles_.push_back(new Car(...));
vehicles_.push_back(new Motocycle(...));
Since we're using unique_ptr
here instead of a raw pointer, there's no need to explicitly delete
.
By making the class polymorphic you can declare functions on the base class and implement class-spefici functionality by providing definitions in the derived classes. This makes it possible to call methods through a pointer to the base class without having to cast to the derived type.
If you need to call methods that exist only on a derived class, then you will need to cast the pointer. This should be done using dynamic_cast
, and requires that your class is polymorphic.
EDIT:
Your comments suggest that you don't know how to use a vector
and would prefer to use a raw array. That's fine too. Here's a simplified example that uses a C-style array of raw pointers. Note that by using neither vector
nor a smart pointer like unique_ptr
you make your code more brittle and prone to errors, and you often have to use a Magic Number for the array size (which is gross).
Vehicle* vehicles_[100];
vehicles_[0] = new Car(...);
vehicles_[1] = new Motorcycle(...);
Upvotes: 2