Archived

This topic is now archived and is closed to further replies.

A linked list of super-classes

This topic is 6081 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I have a small problem. I am working on a RPG and I have started to work on items in the game. I am making a linked list of Items in the game. But there are different types of Items that all need extra stats and info based on thier type of Item. Like a sword or a piece of armor. I want to be able to link the super classes which contains the universal information of the Items. Then have sub classes that contain the different info needed for stuff like armor, weapons, etc. What I may do is make several linked list''s of Items and overload the constructor. I was hoping someone could tell me how or if I could just link the super-classes not just the sub-classes. Thx for your time. Minerjr

Share this post


Link to post
Share on other sites
Here's how to do what you want.

1. Place all of the common variables into a class or structure.


struct item
{
string name;
int weight, value;

item(const string& name, int weight, int value)
: name(name), weight(weight), value(value) {}
};



2. Then place the specialized information into the derived classes:


struct weapon : public item
{
int damage, accuracy;
magic spell; // some struct that holds spell info and charges

weapon(const string& name, int weight, int value, int damage, int accuracy, const magic& spell)
: item(name, weight, value),
damage(damage), accuracy(accuracy), spell(spell) {}
};

struct quest_item : public item
{
int checkpoint;

quest_item(const string& name, int checkpoint)
: item(name, 0, 0), checkpoint(checkpoint) {}
};



3. Now you can store a linked list of any derived classes using a pointer to the base object (i.e., item).


#include <list>

using std::list;

int main()
{
// declare a list of items
list<item*> items;

// add some items to the end of the list
items.push_back(new weapon("long sword", 20, 80, 10, 10, magic("boost", 20, 10));
items.push_back(new quest_item("letter of introduction"), 1);

// since we allocated the items with new, we must delete them
for( list<item*>::iterator i = items.begin(); i != items.end(); ++i )
delete (*i); // *iterator == stored element, i.e. item*

// now destroy the invalid pointers
items.erase();
}



Edited by - null_pointer on April 23, 2001 11:37:54 AM

Share this post


Link to post
Share on other sites