C++ How to create subclass in class with array
Hi guys, i still learning C++ and face some issues here.
Basically i got a parent class
lets call this parent class as
Vehicle
It got 2 sub class, lets assume they are
Car and Motorcycle
I will create a vehicle object assume vehicle size is 20
Vehicle veh[20]
I will do the following
string vType;
cout << "Please enter your vehicle Type:";
cin >> vType;
so i do a comparision if (vType==”Car”)
it will return 4 wheels from the sub class, but how do i declare its 4 wheels at Car and 2 wheels at Motorcycle , i know i need create 2 additional cpp file which is
class Car : public Vehicle
{
private:
int noOfWheels;
public:
computePrice();
}
But how do i set noOfWheels specially to Car as 4 and Motorcycle as 2.
The next is the tricky part.. after knowing how many wheel it is
i will need store a array for each wheel
string wheel[4];
since i know there 4 wheel in cars.
How do i prompt 4 type and store it in an array, and all of this in an object call Vehicle.
I can use a for loop and thats not the issue, the part i am stuck on is how do i create a string array and store the 4 prompt and then into this Vehicle[0]
wheel 1:
wheel 2:
wheel 3:
wheel 4:
When user want to print data it will be
Vehicle[0]
Type: Car
Wheel: 4
Wheel[0] = Fine condition
Wheel[1] = Need to check again
Wheel[2] = Fine condition
Wheel[3] = Might need get repair
Thanks for all help.
Firstly the declaration for your array is wrong. Since you are dealing with polymorphic classes you need to use pointers.
Otherwise you will have what is called object slicing. Which means that even if you create a
Caror aMotorcyclethey will be converted intoVehicles when you assign them to your array.‘how do i set noOfWheels specially to Car as 4 and Motorcycle as 2.’
In the constructor
But personally I don’t think you need a noOfWheels data member at all. Since the number of wheels is fixed for each type of Vehicle it’s a waste of space, instead you need a virtual function
‘how do i create a string array and store the 4 prompt and then into this Vehicle[0]’
Again I would use the constructor to initialize the car wheel names.
Use constructors to initialize classes. That’s what they are for.