Derived class objects in singly linked list stack

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

// 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();





Last edited on
ListNode holds pointers to Creatures, not fighters. Is this an oversight?
Sorry, that was a small error. Creature = Fighter. I just didn't copy and paste it correctly over here. Fixed that.
Last edited on
Where are you trying to push a Jester? And what do you mean by "doesn't work"? Does it crash? Output something funky? Fail to compile?
Last edited on
Topic archived. No new replies allowed.