In: Computer Science
Define a class template called genericStack for storing any data type in a static stack. Your class template must include a constructor, a destructor, push, pop, peek, isFull, and isEmpty functions (no display function is required). Write a simple main function in your program that demonstrates the class template with a stack of strings.
#include <iostream>
using namespace std;
// Class for stack
template <class ItemType>
class genericStack{
private:
ItemType *info;
int top;
public:
genericStack();
bool isEmpty();
bool isFull();
void push(ItemType x);
void pop(ItemType &x);
// destructor
~genericStack();
};
// Constructor to initialize stack
template <class ItemType>
genericStack<ItemType>::genericStack()
{
info = new ItemType[5]; // set 5 as max
top = -1; // assign -1 to first element
}
// Utility function to check if the stack is empty or not
template <class ItemType>
bool genericStack<ItemType>::isEmpty()
{
return top == -1; // true for empty
}
// Utility function to check if the stack is full or not
template <class ItemType>
bool genericStack<ItemType>::isFull()
{
return top == 5 ; // top become size
}
// function to add an element x in the stack
template <class ItemType>
void genericStack<ItemType>::push(ItemType x)
{
if (isFull())
{
cout << "Stack is
Full.\n";
return;
}
info[++top] = x; // push item to stack
}
// function to pop top element from the stack
template <class ItemType>
void genericStack<ItemType>::pop(ItemType &x)
{
// check for stack underflow
if (isEmpty())
{
cout << "UnderFlow Stack is
Empty \n";
return;
}
// // decrease stack size by 1 and copy to x
x = info[top];
top = top - 1;
}
// Destructor
template <class ItemType>
genericStack<ItemType>::~genericStack(){
delete [] info; // delete stack
}
int main(){
genericStack<string>obj; // create object of
string
string elem; // to get popped element
// pushing
obj.push("Ram");
obj.push("albert");
obj.push("newton");
obj.pop(elem);
cout<<elem<<endl; // newton since last in
first out
obj.pop(elem);
cout<<elem<<endl;
obj.pop(elem);
cout<<elem<<endl;
}
/* OUTPUT */