0

I am trying to solve why my copy constructor refuses to work.

I have class Car:

class Car{

private:
char* make;
int license_number;
int owner_ID;
Car* next;


public:
//constructor with data presentation
Car(char* name, int number, int id);
//destructor with data presentation - for further use
~Car();
//Rest of methods
Car*& GetNext();
char*& GetMake();
int& GetLic();
int& GetID();
void Print();
};

and Class CarList

class CarList{

private:
Car* head;


public:
CarList();
~CarList();
CarList(const CarList & old);
void add_car(char* name, int number, int id);
void remove_make(char* name);
void print();
};

The thing is, I want to create a copy constructor for CarList. To archieve that i wrote:

CarList::CarList(const CarList & old)

{
    cout<<"Copy constructor initiated. " <<endl;

    Car* newhead=old.head;
    Car* temp=NULL;

    while(newhead)
    {
        Car* cp = new Car(*newhead);
        if(temp) temp->GetNext()=cp;
        else head=cp;

        newhead=newhead->GetNext();
        temp=cp;
    }
}

Everything except every 'make' gets copied properly. Every make appears to be thrash in console.

I suspect that it might be due to deleting old list (when old list is not deleted makes are okay). How can I change my copy-constructor to keep makes after deleting? It is a bit different because I don't know how can I access char* make from Car in copy constructor while doing deep-copy (compiler says it is private; friendship is not allowed).

Rick Smith
  • 9,031
  • 15
  • 81
  • 85
MikelThief
  • 185
  • 1
  • 13
  • You have a rule of three violation. No explicit copy constructor for the `Car` class. The linked to dupe target shows you how to fix it. – NathanOliver Apr 05 '16 at 17:24
  • I don't have a problem with single class. Problem is when I need to access member of Car class from Carlist (when doing deep-copy). I don't want to use friendship. – MikelThief Apr 05 '16 at 17:50
  • You said `make` becomes garbage. This is because `car` does not have a deep copy copy constructor. Add an actual copy constructor to `Car` and see what happens. – NathanOliver Apr 05 '16 at 17:52

0 Answers0