title: How do I implement the stack::top() function?
body: <p>my question is how do I implement the Stack::top() function without using the std::stack library? In other words, how do I write my own top() function that returns the top element of the stack without popping it for my following stack?</p>
  
  <p>Thanks.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdexcept&gt;
  
  using namespace std;
  
  class Stack
  {
  private:
      int *p;
      int top,length;
  
  public:
      Stack(int = 0);
      ~Stack();
  
      void push(int);
      int pop();
      void display();
  };
  
  Stack::Stack(int size)
  {
      top=-1;
      length=size;
      while(length &lt;= 0)                //If the stack size is zero, allow user to mention it at runtime
      {
          cout&lt;&lt;"Stack of zero size"&lt;&lt;endl;
          cout&lt;&lt;"Enter a size for stack : ";
          cin &gt;&gt; length;
      }
      p=new int[length];
  }
  
  Stack::~Stack()
  {
      delete [] p;
  }
  
  void Stack::push(int elem)
  {
      if(top==(length-1))     //If the top reaches to the maximum stack size
      {
          throw overflow_error("Can't push onto a full stack");
      }
      else
      {
          top++;
          p[top]=elem;
      }
  }
  int Stack::pop()
  {
      if(top==-1)
      {
         throw underflow_error("Can't pop from an empty stack");
      }
      int ret=p[top];
      top--;
      length--;
  
      return ret;
  }
  
  void Stack::display()
  {
      for(int i = 0; i &lt;= top; i++)
          cout&lt;&lt;p[i]&lt;&lt;" ";
      cout&lt;&lt;endl;
  }
  
  int main()
  {
      int len;
  
      cout&lt;&lt;"Enter a size for stack : ";
      cin &gt;&gt; len;
      Stack s1(len);
      try{
          s1.push(1);
          s1.display();
          s1.push(2);
          s1.push(3);
          s1.push(4);
          s1.push(5);
          s1.display();
          s1.pop();
          s1.display();
          s1.pop();
          s1.display();
          s1.pop();
          s1.display();
          s1.pop();
          s1.display();
          s1.pop();
          s1.display();
      }
      catch(overflow_error){
          cerr&lt;&lt; "Illegal operation. Cannot push onto a full stack.";
          return -1;
      }
      catch(underflow_error){
          cerr&lt;&lt; "Illegal operation. Cannot pop from an empty stack.";
          return -1;
      }
  }
  </code></pre>