Image

Stack class in c++.

Hello!
About two days ago I was writing a stack data structure in C++ and bumped into a strange problem.
Here is the code:




/*stack.h*/
template <typename T>
class stack{
   
    public:
    stack();
    ~stack();
    void push(T);
    T pop();
   
    protected:
    T* s;   
    int el_c; //element count
};

/*stack.cpp*/
#include "stack.h"
#include <cstdlib>

template <typename T>
stack<T>::stack(){
    s=NULL;
    el_c=0;
}

template <typename T>
stack<T>::~stack(){
    if(s!=NULL) free(s);
}

template <typename T>
void stack<T>::push(T element){
    s=(T*)realloc(s, (el_c+1)*sizeof(T));
    s[el_c++]=element;
}

template <typename T>
T pop(){
    return s[--el_c];
}

/*stack-test.cpp*/
#include "stack.h"
#include <iostream>
int main(){
    stack<int> s1;
    s1.push(8);s1.push(9);
    /*This  code works correctly - the output is 9 8*/
    std::cout<<s1.pop()<<" ";
    std::cout<<s1.pop()<<"\n";
    /*But if we write
    std::cout<<s1.pop()<<" "<<s1.pop();
    the output will be 8 9!!
    Why?!
    */
    return 0;
}