Let header files include each other

Hi.
Im new to C++ and have currently a problem.

One class A contains pointers to another class B, but i now also need to have pointers from class B to class A. More precise i want to implment a bi-directed edge between those classes.

What i have tried to do is making there header files include each other:

Class A
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef EDGEOVERLAYNODE_H_
#define EDGEOVERLAYNODE_H_
#include "../LocalVersionTree/LocalVersionNode.h";

class EdgeOverlayNode {
public:
	EdgeOverlayNode();
private:
LocalVersionNode *edgeVersionPointer;
LocalVersionNode *edgeVersionBackPointer;
};

#endif /* EDGEOVERLAYNODE_H_ */ 



Class B
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#ifndef LOCALVERSIONNODE_H_
#define LOCALVERSIONNODE_H_
#include <string>
#include "../EdgeOverlay/EdgeOverlayNode.h";

using namespace std;

class LocalVersionNode {
public:
...
private:
	//vector<EdgeOverlayNode>
};

#endif /* LOCALVERSIONNODE_H_ */



But this makes a cycle and the compiler gives an error:
../LocalVersionTree/../EdgeOverlay/EdgeOverlayNode.h:16:1: error: ‘LocalVersionNode’ does not name a type


Does any know the solution?
I have read some place that you then need to make a common header file!
Is that really true?
The article ne555 linked to is definitely worth a read. Though to more directly address your immediate problem:

- LocalVersionNode actually uses EdgeOverlayNode objects. Therefore edgeoverlaynode.h is an include dependency and localversionnode.h should #include "edgeoverlaynode.h"


- EdgeOverlayNode does not actually use LocalVersionNode objects (it only uses pointers). Therefore localversionnode is not an include dependency, and edgeoverlaynode must not include that header.

- Rather, LocalVersionNode is a forward declared dependency to EdgeOverlayNode, and the class can be forward declared instead of #included.


Read ne555's link for more details on these concepts.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef EDGEOVERLAYNODE_H_
#define EDGEOVERLAYNODE_H_
// #include "../LocalVersionTree/LocalVersionNode.h"; // <- do not do this
class LocalVersionNode;  // <- do this instead

class EdgeOverlayNode {
public:
	EdgeOverlayNode();
private:
LocalVersionNode *edgeVersionPointer;
LocalVersionNode *edgeVersionBackPointer;
};

#endif /* EDGEOVERLAYNODE_H_ */  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef LOCALVERSIONNODE_H_
#define LOCALVERSIONNODE_H_
#include <string>
#include <vector> // <- using vector, so #include it
#include "../EdgeOverlay/EdgeOverlayNode.h" // <- this is OK, we are actually using these objects here

//using namespace std;  //<- try to avoid putting this in header files, as it completely
   // defeats the entire point of having a namespace

class LocalVersionNode {
public:
...
private:
	std::vector<EdgeOverlayNode> whatever;  // <- this will work now
};

#endif /* LOCALVERSIONNODE_H_ */ 
Topic archived. No new replies allowed.