Rather scarily the code compiles as-is with (the MinGW version of) GCC 4.8.1 :-(
(But it fails to compile with Visual Studio, with "error C2229: class 'Stack' has an illegal zero-sized array")
Line 22 is valid but rather pointless; why access the member of an array but then not use it? And if max is the size of the array, then you're trying to access the element just after the end of the array.
The line which concerns me more is line 14 -- the zero size array. Apparently an extension from C (but according to the C standard only the last member of a struct is allowed to be "flexible"?)
The output is:
----------
8
----------
----------
4201936
----------
----------
2359088
----------
----------
2359200
----------
----------
4199443
----------
----------
0
----------
----------
0
----------
----------
0
---------- |
Counting the output lines I see that there are 8 lines, so setting
myarray[0]
is trampling on
top
as
myarray
has been declared with a size of zero. This is not legal in standard C++.
Adding "-std=c++11" to my compiler options didn't stop the code from building with GCC as expected? :-(
But adding -Wpedantic ("Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, ...") I get
.../test/main.cpp:14:13: warning: ISO C++ forbids zero-size array 'myarray' [-Wpedantic]
And adding -Wall -Wextra spots the pointless array index operator usage.
.../test/main.cpp:22:16: warning: statement has no effect [-Wunused-value]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
#include <iostream>
using namespace std;
class Stack{
public:
Stack(const int size);
~Stack(); // add destructor
void push_back(int value);
void print();
private:
int max;
//int myarray[];
int* myarray; // now a pointer
int top = -1;
};
Stack::Stack(const int size) : max(size), myarray(new int[size])
{
//max = size;
//myarray[max];
}
Stack::~Stack()
{
delete [] myarray; // free memory
}
void Stack::push_back(int value)
{
top++;
if(top < max)
{
myarray[top] = value;
}
else{
cout << "stack is full"<<endl;
top--;
}
}
void Stack::print()
{
//for(int i = 0; i <top;i++)
for(int i = 0; i <=top;i++) // need <= not <
{
cout << "----------" << endl;
cout << myarray[i] << endl;
cout << "----------" << endl;
}
}
int main()
{
Stack object(10);
object.push_back(8);
object.print();
}
|
The main change is to replace the zero size array with a pointer; C++ allow allows fixed sized arrays, so if you want to determine the size at runtime you need to use a pointer. Also fixed loop termination condition.
(Of course, in real life -- rather than an exercise -- you'd use std::vector rather than an array. And std::stack instead of a custom one...)
Andy
PS When using GCC for educational purposes, you should consider specifying the standard (e.g. -std=c++11) and crank up the error level (-Wall -Wextra -Wpedantic)