Using Array To Hold Five Class Members

I want to use an array to hold five vehicle class members. Am I writing the array correctly?
 
Last edited on
Some suggestions:

class Vehicles class Trucks

This is a stylistic thing, but I think it's better to avoid plurals in class names, unless of course that is exactly the behavior your class is supposed to encapsulate. It just confuses everybody. You wouldn't say: "A vehicles has two wheels". Avoid it for the same reason that int isn't ints and std::string isn't std::strings. I shouldn't have to guess what a single instance of your class actually is.

Also, member names like string vehicleName; are redundant. We know it's the name of a vehicle by virtue of the fact that it belongs to a vehicle. Why not just std::string name;?

A Truck is a vehicle, no? It should probably be inheriting from Vehicle.

1
2
const int number = 5;
Vehicles vehicle[number];


I think number deserves a better name.
constexpr int num_vehicles = 5;

Alternatively, you can initialize the vehicles in your array like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>

struct Vehicle {
	std::string name;
	int num_passengers;
	int num_wheels;
	int max_speed;
};

int main() {

	constexpr int num_vehicles = 2;

	Vehicle vehicles[num_vehicles] = { {"Unicycle", 1, 1, 8}, {"Bus", 100, 4, 20} };

	return 0;
}
Last edited on
vehicle[0].setALL("Unicycle", 1, 1, 80); and etc.
This is how I ended up initializing the values.
But I'll try that out and see how it works. Thank you!

EDIT:

Just realized you changed it to a struct. It was supposed to be a class.
Last edited on
Topic archived. No new replies allowed.