Why does it crash when I get to the copy constructor function?
In the copy procedure that you will find in my class definitions, I’m making sure that the Queue that will be created as a copy of some other original Queue is empty before copying begins: let’s say Queue q1 is not empty and I want to turn q1 into q2. I want to empty the contents of q1 before copying the contents of q2 to q1..
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
class Dnode
{
public:
Dnode(int);
int n;
Dnode* l, *r;
};
Dnode::Dnode(int tx)
{
n = tx;
l = r = NULL;
}
class Queue // reminder: insertions at the rear, deletions at the front
{
public:
Queue();
void enqueue(int x);
int dequeue(void);
bool empty(void) const;
void display(void) const;
Queue(const Queue&); //copy constructor
private:
Dnode* front, *back;
void copy(Dnode*);
void free();
};
Queue::Queue()
{
front = back = NULL;
}
void Queue::enqueue(int x)
{
Dnode* d = new Dnode(x);
if (empty())
front = back = d;
else
{
back->r = d;
d->l = back;
back = d;
}
}
int Queue::dequeue(void)
{
assert(! empty());
Dnode* temp = front;
front = front->r;
if (front == NULL)
back = NULL;
else front->l = NULL;
int x = temp->n;
delete temp;
return x;
}
bool Queue::empty(void) const
{
return front == NULL;
}
void Queue::display(void) const
{
for (Dnode* d = front; d != NULL; d = d->r)
cout << d->n << " ";
cout << endl;
}
void Queue::copy(Dnode* dn) // "dn" will be "Front" of Queue being copied
{ // this procedure will be called in Copy Constructor
Dnode* temp=front; // found underneath this procedure
while(front!=back)
{
front=front->r;
delete temp;
temp=front;
}
delete temp;
front=back=temp=NULL;
if(dn!=NULL)
{
while(dn->r!=NULL)
{
enqueue(dn->n);
dn=dn->r;
}
enqueue(dn->n);
}
}
Queue::Queue(const Queue& x)
{
copy(x.front);
}
int main()
{
Queue q;
if (q.empty()) cout << "q empty" << endl;
for (int i = 0; i < 10; i++) q.enqueue(i);
q.display();
int x = q.dequeue();
cout << "x is " << x << endl;
q.display();
Queue q1(q); //<----program crashes when we get here
q1.display();
}
You’re confusing a copy constructor with an assignment operator. In an assignment operator, you have to delete the current queue and replace it with a copy of the second parameter. But this is a copy constructor. There is no current queue. Your members are uninitialized. So when you begin by trying to delete the existing queue, you’re messing with uninitialized pointers.