Insertion of abstract array element using templates

  abstract, c++, templates

6I’m working on a program that allows to stack numbers independent from their type and print it.
Everything works perfect but unfortunately it seems the first array element is always completely off.

The code lets expect that it returns:

6 5 4 3 2 1

However, compiling the code leads to:

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;
}

Source: Windows Questions C++

LEAVE A COMMENT