Class and delete function

Hi everyone, i am working on this assignment and there are something i dont understand
1st:Change the push function. It will take a parameter that is a Car by constant reference. It will allocate space in the heap for one Car object that is a copy of the Car parameter and then put the pointer to that Car in the array. Then it will increment the carCount.

and this is my solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* **********StringofCars-member-function-push*********
 add one car to the array
 */
void StringOfCars::push(const Car &obj)
{
    ptr = new Car*;
    Car carA;
    **ptr = carA;
    carCount++;
    if (carCount >= 9)
    {
        cerr << "error" << endl;
        exit(3);
    }
}


2nd: The copy constructor will get space for the array of Car* elements and set them to zero. It will set the carCount to zero. Then it will use the push function to push each each Car object into the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    StringOfCars(const StringOfCars & obj)
    {
        Car ** ptr = new Car*[ARRAY_SIZE];
        carCount = obj.carCount;
        for (int i = 0; i <= ARRAY_SIZE; i++)
        {
            *(ptr + i) = 0;
        }
        carCount = 0;
        for (int i = 0; i<carCount; i++)
        {
            *(ptr + i) = *(obj.ptr + i);
        }
        


3rd and 4th: The pop function will take a Car parameter by reference. It will copy the Car to the reference parameter. Then it will delete the Car from the heap. It will set the entry in the array that is no longer used to 0. It will decrement the carCount.
The destructor will need to delete each Car pointed to by the array, and then delete the array.
for those require i am really struggling on them.
Please help me
Last edited on
Topic archived. No new replies allowed.