Saturday, 15 January 2011

c++ - Why does my stack object change a default value after being created? -



c++ - Why does my stack object change a default value after being created? -

so have stack created below. variable top supposed represent current index, or "top index". doing testing, constructor does called , value of top is -1 while programme still running constructor method. however, after creating stack object, , testing see value of top is, maintain getting top 32767. literally, main create new stack as

stack s; //testing while running see value of top... -1 //testing here see value of top... 32767

-

the stack created shown below.

#ifndef __stack_h_ #define __stack_h_ class stack{ int stacksize; int top; char* items; public: stack(); ~stack(); void push(char c); char pop(); bool isfull(); bool isempty(); }; #endif

and implementation below:

/* stack implementation file */ #include "stack.h" #include <iostream> using namespace std; stack::stack(){ cout << "ctor run." << endl; stacksize = 10; //stack size 10 int top = -1; //currently empty stack cout << top << endl; items = new char[stacksize]; } stack::~stack(){ //destructor delete[] items; } void stack::push(char c){ //push next stack items[++top] = c; cout << top << endl; } char stack::pop(){ //pop 1 stack homecoming items[top--]; } bool stack::isfull(){ //checks see if stack total if (top + 1 == stacksize) homecoming true; } bool stack::isempty(){ //checks see if stack empty if (top == -1) homecoming true; }

you want top = 1 not int top = 1 in constructor. former assigns member, latter initialises local variable goes out of scope @ end of constructor.

c++ class object stack

No comments:

Post a Comment