Johnrad
Johnrad

Reputation: 2655

C++ - Linked List Stack Operator Overloading Function

I am currently working on a stack that implements linked list. I am having a problem when it comes to overloading the "=" operator. I am very clueless as to what to do. If anyone could point me in a good direction that would be awesome.

//operator overload
template <class S>
const Stack<S>::operator=( const Stack& s )
{

    if (s.isEmpty())
        theFront = theTop = 0
    else
    {
        NodePointer temp = q->theFront;

        while(temp != 0)
        {
            push(temp->data);
            temp = temp->next;
        }
    }

    return *this;
}

I am also getting this error : Stack, std::allocator > >::Node::Node(std::basic_string, std::allocator >)' referenced from C:\USERS\JOHNNY\DESKTOP\STACK\INFIX_TO_RPN.OBJ

Can this be fixed by my operator overload function?

Upvotes: 2

Views: 2334

Answers (2)

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74430

You need to empty the current stack, before pushing data on it. You should add a removeAll function, and call it at the top of the assignment (after a check for self assignment, which is also a good idea). Otherwise, it looks correct. So, the end result would be:

//operator overload 
template <class S> 
const Stack<S>::operator=( const Stack& s ) 
{ 
    // Check for self assignment
    if (&s==this)
        return *this;

    // Clear the current stack
    removeAll();

    // Copy all data from stack s
    if (!s.isEmpty())
    { 
        NodePointer temp = q->theFront; 

        while(temp != 0) 
        { 
            push(temp->data); 
            temp = temp->next; 
        } 
    } 

    return *this; 
} 

Here is a sample removeAll function:

template <class S> 
void Stack<S>::removeAll()    
{ 
    while (s.theFront)
    {
        NodePointer p = s.theFront;

        s.theFront = s.theFront->next;
        delete p;
    }

    s.theTop = s.theFront;
}

Upvotes: 2

James McNellis
James McNellis

Reputation: 355217

Instead of manually implementing the copy assignment operator for your class, use the copy-and-swap idiom.

Once you've implemented a swap() function for your class (the article to which I linked above provides an excellent description of how to do this), the operator= overload becomes short and simple:

Stack& operator=(Stack rhs)
{
    swap(rhs);
    return *this;
}

Upvotes: 1

Related Questions