I am trying to fix a problem related to overloading assigment operator to be able to assign one list to another.
I have two classes:
class CarList{
private:
Car* head;
void clear();
public:
CarList();
~CarList();
CarList(const CarList & olist);
CarList & operator= (const CarList & olist);
void add_car(char* name, int number, int id);
void remove_make(char* name);
};
and
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);
Car(const Car &car);
//destructor with data presentation - for further use
~Car();
//Rest of methods
Car*& GetNext();
char* GetMake();
int GetLic();
int GetID();
int SetID(int id);
void Print();
};
I wrote following method to overload an operator:
CarList& CarList::operator= (const CarList & olist)
{
clear();
if (this == &olist) return *this; // detecting if target is same as source
if(this->head != NULL) this->head=new Car(*olist.head);
return *this;
}
which calls Car copy constructor:
Car::Car(const Car &car)
{
this->make = new char[strlen(car.make)+1];
strcpy(this->make, car.make);
this->license_number = car.license_number;
this->owner_ID = car.owner_ID;
if (car.next != NULL)
this->next = new Car(*car.next);
else
this->next = NULL;
}
but program crashes and I don't really know why. Copy constructor in Carlist works totally okay using Car copy constructor call.