Prolle
Prolle

Reputation: 61

Deep copy of a queue using assignment operator

I have troubles with the pointers using my assignment opperator, it doesn't make a new qeueu, instead the new array points to the old one. So when I delete in the new queue the values in my old queue changes.

First off all I can see that my copy constructor isn't called in my main for some unknown reason, the problem is probably related with that.

Some of my main code used to illustrate the problem:

aQueue.enqueue(10);
    aQueue.enqueue(20);

    Queue<int> cQueue = aQueue;             

    cout << "aQueue: "; aQueue.printQeueue(2, 0);
    cout << "cQueue: "; cQueue.printQeueue(3, 0);

    cQueue.dequeue();
    cout << "aQueue: "; aQueue.printQeueue(4, 1);
    cout << "cQueue: "; cQueue.printQeueue(5, 1);
    system("pause 4");

This is where the problems start, if I enqueue aQueue with 10 and 20 and then assign cQueue to aQueue, if I print aQueue the result is: 10 20. After that dequeue cQueue and print aQueue the result is: -179016023. If I print cQueue the result is: 20, as it should be.

The output: https://i.sstatic.net/0xRwC.jpg

Here follows the functions used direct or indirect:

template <typename T>
T Queue<T>::dequeue(){

    T temp = front();

    Node *old = fronten;
    fronten = fronten->next;

    delete old;

    return temp;

}


template <typename T>
Queue<T>::Queue(const T &rhs){

    Node *tempfront = rhs.fronten;

    while (tempfront.fronten!=rhs.back){
        enqueue(tempfront);
        tempfront = tempfront->next;


    }
}

template <typename T>
void Queue<T>::enqueue(const T& item){


    if (isEmpty()){
        back = fronten = new Node(item);
    }
    else
        back = back->next = new Node(item);
}

Node(const T &theElement, Node *n = nullptr): element(theElement), next(n) {};

Upvotes: 0

Views: 2708

Answers (1)

4pie0
4pie0

Reputation: 29744

You don't have at the moment copy constructor for your Queue class (or you don't show it). Yours

template <typename T> Queue<T>::Queue(const T &rhs)

is constructor for Queue from the type it stores. You need something like:

template <class T>
class Queue
{
  public:
    Queue( const Queue &);                // copy ctor
    Queue& operator=( const Queue& q);   // assignment operator
  //...
}; 

Upvotes: 2

Related Questions