Answer the question
In order to leave comments, you need to log in
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;
}
Queue::Queue(const Queue &obj) {
arr = obj.arr;
maxCount = obj.maxCount;
count = obj.count;
std::copy(obj.arr, obj.arr + count, arr);
}
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++;
}
}
Answer the question
In order to leave comments, you need to log in
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;
};
}
Queue * q1 = new Queue("test");
Queue q2(*q1);
delete q1;
std::cout<<q2.name; //Утечка памяти
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;
}
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 questionAsk a Question
731 491 924 answers to any question