Reputation: 3065
Im having a little problem with classes. Here is some of my code:
//GameMap.h
#ifndef GAMEMAP_H
#define GAMEMAP_H
#include "apath.h"
class GameMap
{
/*class definition here*/
};
#endif
and
//apath.h
#ifndef APATH_H
#define APATH_H
class path
{
//some code...
void DoSomething(GameMap map);
//rest of class body
};
#endif
I cant use GameMap in apath.h, when I try to include "GameMap.h in this file I get some stupid errors... I also tried to add class GameMap; before definition of path class. Nothing helped... I really need to use it here... If needed I can post some more code.
Thanx for any replies!
Upvotes: 0
Views: 2367
Reputation: 42133
You should use forward declaration of class GameMap
in apath.h:
class GameMap; // forward declaration
class path
{
//some code...
void DoSomething(GameMap map);
//rest of class body
};
Check: When can I use a forward declaration?
In following example I use forward declaration of class A
so that I'm able to declare function useA
that uses it:
// file a.h
class A;
void useA(A a);
and then in main.cpp I have:
#include "a.h"
class A
{
public:
void foo() { cout << "A"; }
};
void useA(A a)
{
a.foo();
}
which is absolutely correct, since class A is already defined here.
Hope this helps.
Upvotes: 4
Reputation: 23644
make external declaration in apath.h
class GameMap;
After it change signature of method:
void DoSomething(GameMap& map);
Or
void DoSomething(GameMap* map);
Upvotes: 1
Reputation: 485
You're trying to do circular includes, which are obviously forbidden.
I'd suggest you forward declare GameMap in apath.h and pass it as a const reference:
class GameMap; // forward declaration
class path
{
//some code...
void DoSomething(const GameMap &map);
//rest of class body
};
const ref is better than simple ref since it tells explicitly that the object cannot change during the function call.
Upvotes: 1
Reputation: 7744
You should check PIMPL idiom.
In path header:
class GameMap;
class Path
{
public:
void useMap( GameMap * map );
};
In path source:
#include "Path.h"
#include "GameMap.h"
void Path::useMap( GameMap * map )
{
// Use map class
}
More links: link and connected topic.
Upvotes: 2
Reputation: 14478
You have a circular include problem. GamePath.h includes apath.h, so trying to include GamePath.h in apath.h is brittle at best and gives errors (your case) at worst. The best bet is to find which pieces of apath.h are used by GamePath.h, and refactor those into a common header file, say common.h, and include common.h in both GamePath.h and apath.h. That way you don't have a circular include anymore, and you can draw a graph of includes as a nice beautiful DAG.
Upvotes: 1