Reputation: 103
consider these classes (simplified)
class Character
{
public:
char name[20];
char type[20];
int strength;
};
class inventoryItem
{
public:
char name[20];
};
class weapon: public inventoryItem
{
public:
int magical resistance;
};
class spell: public inventoryItem
{
public:
int magical power;
};
i have written a class for a linked list (not allowed to use stl list)
class list
{
public:
struct listItem
{
listItem* objectPointer;
listItem* pnext;
}*phead;
list()
{
phead=NULL;
}
bool isEmpty(){
if (!phead)
return true;
else
return false;
}
void addToBack(listItem *itemtoadd)
{
listItem *ptemp;
listItem *ppast;
listItem *pNewItem;
pNewItem=new listItem();
pNewItem->objectPointer=itemtoadd;
pNewItem->pnext=NULL;
if (phead==NULL)
phead=itemtoadd;
else
{
ptemp=phead;
while(ptemp)
{
ptemp= ptemp->pnext;
}
ptemp->pnext=itemtoadd;
}
}
};
I have cut this down a lot but my question is , is there an easy way to create linked lists for all these using the same list class ? or am I wasting my time ?
every time I have tried it cant convert the pointer from type 'weapon' to type 'listitem'
I need a list of characters and a list of each weapon or spell for that character
I'm still a beginner with OOP and pointers ,
the program I have now compiles and I have a list of characters working , however the list is not managed by the class its managed within some other functions, I'm hoping there's a way for one class to deal with it all , can anyone help explain it to me ?
Upvotes: 0
Views: 2691
Reputation: 46
You could use:
enum item
{
WEAPON,SPELL
}
class list {
public:
struct listItem {
union {
weapon *weaponPointer;
spell *spellPointer
} object;
item objType;
listItem* pnext;
}*phead;
however the catch is you have to access the type member to determine what type of item you are accessing.
Upvotes: 0
Reputation: 87997
The simple answer is to do this
struct listItem
{
void* objectPointer;
listItem* pnext;
}*phead;
A void pointer will allow you to store a pointer to anything. Of course it's then entirely up to you to make sure that you don't lose track of what kind of object you are pointing to. So this approach is risky. The safer approach is templates as has been suggested.
Upvotes: 1
Reputation: 5850
Take a look at C++ Templates. Using templates you can have one list class in terms of reading/writing code, but you can have a list of weapons, a list of items or a list of anything else without having to write WeaponsList, ItemsList and SomethingElseList classes separately.
Upvotes: 1