Cyclic Dependency

I have two class files which have object for each. But when I include them, it gives me error. Can someone tell me how to solve this issue.

HeapNode.h:
#include "Node.h"
class HeapNode
{
public:
uint64_t priority;
unsigned index;
Node *node;
};

Node.h:
#include "HeapNode.h"
class Node
{
public:
unsigned addr;
Node *next;
Node *prev;
HeapNode *hNode;
Node(unsigned initAddr)
{
addr = initAddr;
next = NULL;
prev = NULL;
}
};

Thanks
Two files can't include each other. Choose one of the two and replace the inclusion with
class theOtherClass;

This is known as forward declaration, and is used when two classes depend on each other.
In your special case above, don't use #include at all.

Use helios' suggestion and do this in HeapNode.h

1
2
3
4
5
class Node;
class HeapNode
{
...
};


and this in Node.h

1
2
3
4
5
class HeapNode;
class Node
{
...
};


Now, the reason you can avoid inclusion is, when you only use references or pointers to refer to anotherClass, the compiler doesn't need to know the sizeof anotherClass, so a forward declaration would suffice.

In fact, to keep your #include file dependencies small, it is actually a technique of decoupling, to prefer references and pointers over embedding objects inside one another. In order to avoid long compile times and to minimize coupling in large software systems, forward declarations are very much appreciated over the use of #include.

Of course, if your Node.cpp code invokes HeapNode methods, then you need to include HeapNode.hpp in your Node.cpp. OTOH, if you are just passing pointers and/or references around, you don't even need to #include the headers for anotherClass in your .cpp. This is another reason why it's good practice to put implementation in .cpp when you can, to avoid header file dependencies.

Topic archived. No new replies allowed.