Is it possible to have a generic stack which works for all the primitive and non primitive data types?
This is a very serious question because this is confusing me a lot; look at the code of push method of the integer stack
void Stack::push(int number)
{
Node* newNode=new Node;
if(head==NULL)
{
head=newNode;
topelement=newNode;
current=newNode;
head->object=number;
head->preptr=NULL;
}
else
{
topelement=newNode;
newNode->preptr=current;
current=topelement;
newNode->object=number;
}
}
Now my question is if we make it generic using templates then it can work very well for integers, floats, long, double etc, but what about strings?
For example I have an array in my main program in which I get the string from the user and after that I pass this array to the push method of the stack, now look at the code of push method written for strings only.
void stack::push(char* ptr)
{
if(ptr==NULL)
{
cout<<"\n Can't be pushed";
return;
}
Node* newNode=new Node;
if(top==NULL)
{
head=newNode;
current=top=newNode;
head->preptr=NULL;
int len;
len=strlen(ptr);
head->data=new char[len+1];
strcpy(head->data,ptr);
head->data[len]='\0';
}
else
{
top=newNode;
newNode->preptr=current;
current=newNode;
int len;
len=strlen(ptr);
newNode->data=new char[len+1];
strcpy(newNode->data,ptr);
newNode->data[len]='\0';
}
}
I am required to make this method generic so that it works for all the primitive data types, strings and the user defined objects. How would I do that?