I have to make a copy constructor for a queue class and decided to use enqueue to put the files in, but for some reason it gives a runtime error. so I really need some help in figuring out what is wrong. Thanks in advanced

#include <cstddef>
#include <string>
#include <cstdlib>
#include <iostream>

#include "cpqueue.h"

using namespace std;

CpQueue::CpQueue()
{
	first = NULL;
	last = NULL;
} // end default constructor
//copy constructor
CpQueue::CpQueue(const CpQueue& source)
{
	if(!source.isEmpty())
	{
		Node *orig = source.first;
		char newItem;
		do
		{
			newItem = orig->item;
			cout << newItem
				 << "\n";
			enqueue(newItem);//giving runtime error
			//cout << "your passed here\n";
			
			orig = orig->next;
			
		}while(orig != source.first);
		 		
	}
	else
	{
		cout << "\nError in copy\n";
		exit(1);
	}
}// end copy constructor
//destructor
CpQueue::~CpQueue()
{
	while(!isEmpty())
	{
		dequeue();
	}
	first = NULL;
	last = NULL;
}//end destructor
//methods
// check empty
bool CpQueue::isEmpty() const
{
	return last == NULL;
}// end isempty
//add to queue
void CpQueue::enqueue(char newItem)
{
	//create node
	Node *newPtr = new Node;
	//set data
	newPtr->item = newItem;
	newPtr->next = NULL;
	newPtr->prev = NULL;
	
	//insert new Node
	if(isEmpty())
	{
		first = newPtr;
	}
	else
	{
		last->next = newPtr;
		newPtr->prev = last;
	}
	//new node is always at back
	last = newPtr; 
}
// remove from queue
char CpQueue::dequeue()
{
	char data;
	if(isEmpty())
	{
		cout << "\nError empty Queue.\n";
		exit(1);
	}
	else // queue not empty
	{
		data = first->item;
		Node *temp = first;
		//only one node
		if(first == last) 
		{
			first = NULL;
			last = NULL;
		}
		//more nodes
		else
		{
			first = first->next;
			first->prev = last;//or NULL not circle
		}
		temp->next = NULL;
		temp->prev = NULL;
		delete temp;
		return data;
	}//end else
}//end dequeue
//view first
char CpQueue::getFront() const
{
	if(isEmpty())
	{
		cout << "\n Error queue empty \n";
		exit(1);
	}
	else
	{
		return first->item;
	}
}// end getFront
//overrides
CpQueue CpQueue::operator= (const CpQueue& source)
{
	return CpQueue(source);
}
bool CpQueue::operator== (const CpQueue& source)
{
	
}

Recommended Answers

All 3 Replies

lines 24 and 25. You can't do it like that -- newcopy must be a complete node all to itself, it can not be just a pointer into some other linked list. Allocate it just like you did in the original linked list then copy the data from old node to the new node. After it's all done you should be able to destroy one linked list without affecting the other.

Between line 17 and 18, add the following:

first = NULL;
	last = NULL;

>>lines 24 and 25. You can't do it like that -- newcopy must be
Should have been newItem, not newcopy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.