I'm working on a program to stack numbers independent from their type and print them. Everything works but unfortunately it seems the first array element comes out incorrectly.
Expected output:
6 5 4 3 2 1
Actual output:
6 5 4 3 2 6
Does anybody have any suggestions?
StackI.hpp
#ifndef StackI_hpp
#define StackI_hpp
template <typename T>
class StackI{
public:
virtual void push(T t) = 0;
virtual void print()=0;
};
#endif
Stack.hpp
#ifndef Stack_hpp
#define Stack_hpp
#include <iostream>
#include "StackI.hpp"
using namespace std;
template <typename T>
class Stack:StackI<T>{
protected:
int arraySize;
int elements;
T arr[];
int position;
public:
Stack(int arraySize){
this->arraySize = arraySize; //let user pass array size
arr[arraySize];
elements = 0;
position = 0;
}
//insert new element
void push(T t){
if (elements <arraySize) {
arr[position++] = t;
elements++;
}
}
// print result
void print(){
for (int i = position-1; 0<=i;i--){
cout<< arr[i];
}
}
};
#endif // Stack_hpp
Main.cpp
#include "Stack.hpp"
#include <iostream>
int main(){
Stack<int> d = Stack<int>(6);
d.push(1);
d.push(2);
d.push(3);
d.push(4);
d.push(5);
d.push(6);
d.print();
return 0;
}