Hi all, I am new to C++ and I tried to implement array based stack.
Here is my code. It shows RUN FAILED on running it. Please help me solve this issue. Also, I have removed all the exceptions for stack over flow and under flow to specifically tackle the main issue.
In constructor 'StackArray::StackArray()':
11:13: warning: unused variable 'top' [-Wunused-variable]
In constructor 'StackArray::StackArray(int)':
17:13: warning: unused variable 'top' [-Wunused-variable]
In function 'int main()':
38:16: warning: 'stack.StackArray::top' is used uninitialized in this function [-Wuninitialized]
On lines 11 and 17 you are re-declaring a local top variable, which provides confusion with the member variable with the same name.
In C++11, one can assign values in the class declaration:
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class StackArray{
private:
std::size_t top = 0; // assignment here is the same as a member initialization list
std::size_t capacity =10;
int* array = newint[capacity]; // should avoid new, use smart pointers instead std::unique_ptr
public:
StackArray() = default; // use compiler generated constructor
StackArray(int capacityArg)
: //colon introduces a member initialization list - google that :+)
top(0),
capacity(capacityArg),
array (newint[capacity])
{} // nothing to do here
~StackArray() {delete[] array;} // each new must be accompanied by a delete
Line 11: [Warning] unused variable 'top' [-Wunused-variable]
Line 17: [Warning] unused variable 'top' [-Wunused-variable]
Line 38: [Warning] 'stack' is used uninitialized in this function [-Wuninitialized]
At lines 11 and 17 a local variable top is declared instead of using the member variable declared at line 6.
There is also unreachable code, top--; at line 27 can never be executed.
There are a few other issues too, but I'll leave those for now.