yensubldg
yensubldg

Reputation: 21

C++ array with multiple object

This is my code for input list vehicle (can Car or Truck). But it's not work and error: no match for 'operator=' (operand types are 'Vehicle' and 'Car*'). How I can input vehicle (can Car or Truck) for true?

class Vehicle {};
class Car : public Vehicle {};
class Truck : public Vehicle {};

class ListVehicle {
  Vehicle *pVehicle;
  int n;

 public:
  void input() {
    for (int i = 0; i < n; i++) {
      int type;
      cout << "Enter vehicle type (1: car, 2: truck): ";
      cin >> type;
      cin.ignore();
      switch (type) {
        case 1: {
          pVehicle[i] = new Car();
          break;
        }
        case 2: {
          pVehicle[i] = new Truck();
          break;
        }
        default:
          cout << "Invalid type" << endl;
          break;
      }
    }
  }
};

Upvotes: 0

Views: 228

Answers (3)

The problem that I see more important it's that you are trying to increment the memory address of pVehicle, even when you didn't know exactly the size of that object. in order to fix this problem, the best you can do is use one of the standard.

If you already know how much elements will store, and also you know the number of elements will not increase, I suggest you to use the std:array, otherwise if you will increasing commonly adding elements I recommend you use the std::list (this topic it's really dense, if you need to know more look https://www.geeksforgeeks.org/linked-list-vs-array/?ref=leftbar-rightbar).

enum vehicleOpt {car, track/*,.....*/}

class Vehicle {
  pure virtual void foo();
};
class Car : public Vehicle {
   void foo() override;
};
class Truck : public Vehicle {
  void foo() override;
};

void main(){
  std::list<vehicle*> vehicles;
  //std::array<vehicle*, n> vehicles;
  //....

  switch(option){
    case enumOpt::car:
      auto vehicle = new Car();
      break;
    case enumOpt::track:
      auto vehicle = new track();
      break;
      //..... as many case you need. also throw an error if not exist.
   }

   vehicle.foo();
   vehicles.push_back(vehicle);


}

In this approach I also try to use the polymorphism of the vehicle object, and try to reduce the boilerplate code.

Upvotes: 0

yensubldg
yensubldg

Reputation: 21

Here is my workaround

    list<Vehicle *> vehicles;
    case 1:
    {
        Car *car = new Car();
        car->input();
        vehicles.push_back(car);
        break;
    }
    case 2:
    {
        Truck *truck = new Truck();
        truck->input();
        vehicles.push_back(truck);
        break;
    }

Upvotes: 2

Bill Lynch
Bill Lynch

Reputation: 81936

Perhaps you meant to do:

std::array<Vehicle *, 50> pVehicle;

Which would ensure that pVehicle[i] was a pointer.

Upvotes: 1

Related Questions