Archived

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

Header File troubles

This topic is 5704 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

I have two classes ''Character'' and ''Item''. Character needs to be able to use Item instances and Item needs to use Character instances so I included the item header in the character header and vice versa. But when I do this theres some conflict and errors pop up. What am I doing wrong?

Share this post


Link to post
Share on other sites
It''s called circular definitions. You have two problems: the first is that the headers are dependent on each other and therefore recursively include each other (resulting in a parse bomb). Replace one (or both) of the inclusions with a forward declaration like so:

class Item;
 
class Character
{
...
Item item;
...
};

Your second problem is that since each class contains the other, the classes are never closed. ie, Character contains an Item, which contains a Character, which contains an Item, which contains a Character... What you want to do instead is to use pointers, like so:

class Item;
 
class Character
{
...
Item * pItem;
...
};
 
class Item
{
...
Character * pCharacter;
...
};


Hope that helped.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ ]
[ MS RTFM [MSDN] | SGI STL Docs | Boost ]
[ Google! | Asking Smart Questions | Jargon File ]
Thanks to Kylotan for the idea!

Share this post


Link to post
Share on other sites
If they're classes , you might want to use the 'friend' keyword, instead of including them in different header files. Example:


    
#ifndef HEADER1
#define HEADER1

class Items;

class Character
{
private:
blah;
public:
friend Items;
blah;
}

Items
{
private:
blah;
public:
blah;
}




What does it take to be a good game programmer?
---
Good insight,
good knowledge,
and of course,
big money deposits!





[edited by - Wachar on May 6, 2002 7:06:45 PM]

Share this post


Link to post
Share on other sites