Wednesday, 18 May 2016

Using template, write a suitable class declaration and implementation for a generic array class and define a stack class using the array class, where array will support push and pop operations and not the [ ] operator.

#include<iostream.h>
#include<conio.h>
#define MSIZE 5

template <class T>
class Carray{


public:
int size;
T array[MSIZE];
Carray(){
size=0;
}
};
template <class T>
class Stack{
       Carray <T> stack;
       public:
       int push(T item){
   if(stack.size==MSIZE)
   {
   cout<<"Stack OverFLow"<<endl;
   return -1;
   }
   stack.array[stack.size++]=item;
   cout<<item<<" Is pushed into stack"<<endl;
   return 0;
}
       T pop(){
  if(stack.size==0)
  {
  cout<<"Stack UnderFlow"<<endl;
  return -1;
  }
  cout<<stack.array[stack.size-1]<<" Is popped"<<endl;
  return stack.array[--stack.size];
       }

};
void main(){
Stack<int> stack;
int i;
clrscr();
for(i=0;i<6;i++){
   stack.push(i);
}
for(i=0;i<6;i++){
   stack.pop();
}

getch();
}

No comments:

Post a Comment