AmatuerCoder101 AmatuerCoder101 - 3 months ago 8
C++ Question

how to format push_back on a pointer?

I have a function where I want to add pointers into a vector.

#include "Car.hpp"
using namespace std;

bool CarManagementSystem::addCar(Car::CarType new_car_type) {
if (Car::CarType(new_car_type) == (Invalid)) {
return false;
}
else{
new Car::CarType(new_car_type);
carVector.push_back(Car::CarType(new_car_type));
return true;
}
}


The
push_back
command is giving me a lot of grief as in to what form I want the constraints to be in. I want to be able to use this function to create different types of my object Car, however am unsure how to do this.

The car class is purely virtual base class for all my different types of cars.

#include "Car.hpp"

Car::~Car() {
}

Car::CarType Car::type() const {
return AT_INVALID;
}



class CarSystem {
private:
double Balance;
double CarCost;
std::vector<Car*> carVector;
...

Answer

Your vector should be a vector of Car*:

std::vector<Car*> carVector;

The vector should be filled with concrete versions of the cars, meaning classes that are derived from base class Car:

class Van : public Car
{
   ...
};

...

Van* newVan = new Van();

carVector.push_back(newVan);

Here Van* is also a Car*. Make sure that you delete the contents of the vector at some point, or use smart pointers.

A better solution might be to have an enum inside the Car class that states the type of car, and then you don't need to deal with pointers.