Quantcast
Channel: User MikelThief - Stack Overflow
Viewing all articles
Browse latest Browse all 26

Singly linked list copy constructor [duplicate]

$
0
0

This question already has an answer here:

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).


Viewing all articles
Browse latest Browse all 26

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>