D
D
Demigodd2018-04-25 20:07:09
C++ / C#
Demigodd, 2018-04-25 20:07:09

How to properly create Copy Constructor for Class Queue and Double List?

Queue::Queue(const Queue &obj) {
arr = obj.arr;
maxCount = obj.maxCount;
count = obj.count;
}

List::Double_List(): first(nullptr), current(nullptr), last(nullptr), count(0) { }
//Это эквивалентно

List::Double_List() {
first = nullptr;
current = nulltpr;
last = nullptr;
count = 0;
}

How to create a Copy Constructor here?
Queue::Queue(const Queue &obj) {
arr = obj.arr;
maxCount = obj.maxCount;
count = obj.count;
std::copy(obj.arr, obj.arr + count, arr);
}

Can it be like this? Only here it seems like I did not define a new array, that is, does it always copy the value to the same array or not?
But there are problems with the double list, I don’t know how to implement it at all
Copy Constructor for Single Line
List::List(const List& list): head(nullptr), tail(nullptr), count(0) 
{
    for(int i = 0; i < list.getCount(); ++i) 
    {
        Node* temp = new Node();
        temp->data = list[i];
        if(tail == nullptr) {
            head = temp;
        } else {
            tail->next = temp;
        }
        tail = temp;
        count++;
    }
}

Might help)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sddvxd, 2018-04-25
@Demigodd

Explicit copy constructors are declared only in cases where the implicit functionality is not enough, that is, for example, Queue allocates memory dynamically:

class Queue{ 
public:
    char * name;
    Queue(const * char ch){
        name = new char[strlen(ch)+1];
        memcpy(name, ch, strlen(ch)+1); 
    };
    ~Queue(){
        delete [] name;
    };
}

In this case, we need to define an explicit copy constructor and overload the = operator.
The default copy constructor, like the implicit assignment operator, performs a member-by-member copy, which means that if we don’t do everything right, there will be damage and memory leaks:
Queue * q1 = new Queue("test");
Queue q2(*q1);
delete q1;
std::cout<<q2.name; //Утечка памяти

Let's do it right:
Queue::Queue(const Queue & rq){
    delete [] name;
    name = new char[strlen(rq)+1];
    memcpy(name,rq,strlen(rq)+1);
}
Queue & Queue::operator=(const Queue & rq){
    if(this==&rq)return *this;
    delete [] name;
    name = new char[strlen(rq)+1];
    memcpy(name,rq,strlen(rq)+1);
    return *this;
}

Now we get:
Queue * q1 = new Queue("test");
Queue q2(*q1);
delete q1;
std::cout<<q2.name; //test

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question