0

I'm new to C++ and I'm trying to write a CarRental class which contains a vector of pointers to a base class Car. Here's the Car class.

class Car{
public:
    Car():mPlate(""), mBrand(""){}//constructor
    Car(string p, string b): mPlate(p), mBrand(b){} //constructor
    virtual ~Car(){}//destructor

    const string plate() const;
    const string brand() const;

    virtual int numPassengers() = 0;

protected:
    string mPlate;
    string mBrand;
};

const string Car::plate() const{
    return mPlate;
}

const string Car::brand() const{
    return mBrand;
};

And I need to write a class CarRental which contains the container to store the cars. For example,

class CarRental{
public:
    CarRental(vector<Car*> cars){mCars = cars;};
    const vector<Car*>& getCars() const;
    void addCar(Car*);
private:
    vector<Car*> mCars;
};

const vector<Car*>& CarRental::getCars() const{
    return mCars;
}

void CarRental::addCar(Car* c){
    mCars.push_back(c);
}

I doubt whether the class of CarRental I wrote in the right way. I'm considering if I need to write my own copy constructor. And by THE BIG THREE, should I also need assignment operator and destructor? Would three be any memory leaks? How about exception safety?

Xiao Cui
  • 1
  • 2
  • I just read the the post What is The Rule of Three, but I'm still confused. The example given in the post shows that when you have to manage resources in the constructor like const char*. However, I think in this CarRental class I don't need to do anything in the default constructor for it's an empty vector. And only when it's in copy constructor, I do the deep copy. I'm still confused about it. – Xiao Cui Oct 06 '16 at 19:23
  • In your case, the `vector` is not the issue, but what is in the `vector` is a manually managed resource. If you have access to C++11, I advise you to use `std::unique_ptr` as in `std::vector>` and then you will not need to write the Copy Constructor, Assignment Operator or Destructor (the first two will be deleted, the latter will automatically work). If you insist on manual memory management (no C++11 or learning exercise) or need a Copy Constructor then you do have to write all 3: it will necessitate the `Car` class to have a `Car* clone() const` virtual method. – Matthieu M. Oct 18 '16 at 11:20
  • Note: if you have access to Boost, consider `boost::ptr_vector`. – Matthieu M. Oct 18 '16 at 11:20

0 Answers0