Wednesday, 11 September 2013

Copy Constructor and/or pop method in framework for a stack class C++

Copy Constructor and/or pop method in framework for a stack class C++

So I have a stack that is made up of randomly generated strings and then a
pointer to the next item in my .cpp code. I then go through and pop each
item off the stack and print them out. I get a seg fault at the end though
so I'm guessing I'm trying to pop an item one past the stack where I do
not own the memory.
I believe my copy constructor is incorrect - maybe it doesn't set the last
value to null in my stack but I can't figure out why it's not setting the
value to NULL when I put the line
newPrev->next = NULL;
here's my code (class only)
#include <string>
using namespace std;
class Stack
{
protected:
struct Node
{
string item;
Node* next;
}; // struct Node
public:
// constructor of an empty stack
Stack ()
{
head = NULL;
}
// copy constructor
Stack( const Stack & rhs )
{
if (rhs.head == NULL) {// check whether original is empty
head = NULL;
}else{
head = new Node;
head->item = rhs.head->item;
Node* newPrev = head;
// Now, loop through the rest of the stack
for(Node* cur = rhs.head->next; cur != NULL; cur = cur->next)
{
newPrev->next = new Node;
newPrev = newPrev->next;
newPrev->item = cur->item;
} // end for
newPrev->next = NULL;
} // end else
}
// destructor
~Stack ()
{
delete head;
}
// assignment
const Stack & operator=( const Stack & rhs )
{
return *this;
}
// query whether the stack is empty
bool empty () const
{
return false;
}
// add an item to the top of the stack
// this method is complete and correct
void push (const string & new_item)
{
Node* new_node = new Node;
new_node->item = new_item;
new_node->next = head;
head = new_node;
}
// remove the item on the top of the stack
void pop ()
{
if (head!=NULL){
Node *n = head;
head = head->next;
delete n;
}
}
// return the item on the top of the stack, without modifying the stack
string & top () const
{
return head->item;
}
private:
Node* head;
};

No comments:

Post a Comment