Here we have two classes, let’s call it Tree and Fruit. A Tree can only have one or no Fruits at any given time. A Fruit can only be on one Tree. From the Tree object, you can get its Fruit by the function getTreeFruit( ). From the Fruit object, you can get its “owner” by the function getFruitOwner( ) which returns a Tree object.
Now in the Tree header, we have this:
#include "Fruit.h"
class Tree {
private:
Fruit m_Fruit; // The fruit in the tree.
public:
Tree ( Fruit tree_fruit );
Fruit getTreeFruit( ); // Returns m_Fruit.
}
And on the Fruit header:
#include "Tree.h"
class Fruit {
private:
Tree m_Owner; // The Tree object that "owns" the fruit.
public:
Fruit ( Tree fruit_owner );
Tree getFruitOwner( ); // Returns m_Owner.
}
I realized that Tree and Fruit include each other’s header files and this causes an error. How do I go about fixing the error?
Thanks a lot in advanced. 🙂
This is not the only problem. Basically you want two objects to contain each other recursively, which is not possible.
What you probably want is to make fruit have a pointer to the tree it belongs to, and forward-declare
TreeinFruit.hlike so:Tree.h:
Fruit.h