I have a base class, lets call it fighter. I have derived classes of different sort of fighters - Axeman, Jester, etc. I have made a singly linked list stack. My goal is to store derived objects in the singly list stack by pushing them. I have created a modified my push() function so that it takes pointer-to-fighter arguments. However, when I try to add Jester onto the stack, it doesn't work. It compiles in Visual Studio, but I haven't found any evidence that this Jester derived class has been added to the singly linked list stack. I tried to display something from the list to not avail. When I pop() the list, it says there's no elements. I need to know how to store derived class objects all in one singly list stack structure.
// Axeman is the derived class for polymorphism, Fighter is the abstract base class.
Axeman axemanObject;
Figher *fighterObject = &axemanObject;
// trying to push
if (fighterChoice == "Axeman"){
cout << "\n \n \n";
cout << "The Axeman screams and raises his axe." << endl;
cout << "Name: ";
cin >> fighterName;
stackIN.push(&axemanObject);
}
// here's my push function
void Stack::push(Fighter *pointer){
if (head == NULL){
head = new ListNode(pointer);
}
else{
ListNode *nodePtr = head;
while (nodePtr->next != NULL)
nodePtr = nodePtr->next;
nodePtr->next = new ListNode(pointer);
}
}
// I want this to return the creature name that was set
void Stack::displayRoster(){
ListNode *nodePtr = head;
while (nodePtr){
cout << nodePtr->pointer->getCreatureName() << endl;
nodePtr = nodePtr->next;
}
}
// node class
struct ListNode{
Fighter *pointer;
ListNode *next;
ListNode(Fighter *pointerIN, ListNode *next1 = NULL){ /* constructor automatically sets next node to null */
pointer = pointerIN;
next = next1;
}
};
ListNode *head;
Stack() { head = NULL; } /* constructor sets to NULL */
~Stack();
void push(Fighter *pointer); /* functions to add and remove to the singly linked stack */
void pop(); /* remove the top value on the stack */
void displayRoster();