Declare your own class stack : Your stack « Data Types « C++ Tutorial






#include <iostream>
using namespace std;

const int SIZE=100;

class stack {
  int stck[SIZE];
  int tos;
public:
  stack() { 
     tos=0; 
  }
    void push(int i)
    {
      if(tos==SIZE) {
        cout << "Stack is full.\n";
        return;
      }
      stck[tos] = i;
      tos++;
    }
    
    int pop()
    {
      if(tos==0) {
        cout << "Stack underflow.\n";
        return 0;
      }
      tos--;
      return stck[tos];
    }

  operator int() { 
     return tos; 
  }
};

int main()
{
  stack stck;
  int i, j;

  for(i=0; i<20; i++)  stck.push(i);

  j = stck; // convert to integer

  cout << j << " items on stack.\n";

  cout << SIZE - stck << " spaces open.\n";
  return 0;
}
20 items on stack.
80 spaces open.








2.41.Your stack
2.41.1.Declare your own class stack
2.41.2.Generic stack
2.41.3.generic stack implementation
2.41.4.a stack as a class
2.41.5.Stack implementation with constructor