I'm writing a program where I'm supposed to add and delete cars from a Rent-a-Car company. My code works fine, but I'm supposed to overload the += operator to add a car to a dynamically allocated array of objects. Every time I add a car, the array size is required to increase by one. I must not use vectors.
If I don't do any copying, set the dynamic array size to a large number and just do this in operator +=, for example:
cars[numcars] = obj;
numcars++;
return *this;
the code works fine and I'm getting the output; however, if I try to:
- create new object array[size+1]
- copy old array to new array;
- add new object to new array;
- delete old array;
- point original array pointer to new array;
It doesn't work and the program crashes after the first input. I've tried many variations but I can't seem to get where I'm going wrong. I have two classes, one Automobile and one RentACar (where I have the array of objects). In the car class there are 2 constructors (out of which one is copy constructor, operators =, == and << are overloaded and they work fine.
This is my latest attempt at overloading the +=
operator. numcars
is set to 0
RentACar& operator+=(Automobile &obj){
Automobile *temp = new Automobile[numcars+1];
for (int i = 0; i < numcars+1; i++){
temp[i] = cars[i];
}
numcars++;
temp[numcars] = obj;
delete [] cars;
cars = temp;
return *this;
}
and this is the part in main()
for (int i=0;i<n;i++)
{
char marka[100];
int regisracija[5];
int maximumBrzina;
cin>>marka;
for (int i=0;i<5;i++)
cin>>regisracija[i];
cin>>maximumBrzina;
Automobile nov=Automobile(marka,regisracija,maximumBrzina);
//add car
agencija+=nov;
}
The function is expected to make the "cars" array larger by one, and add the new object at the end. Instead, the program crashes after input of maximumBrzina.