How to fix mutual includes compiler error

Dear all,

I just stumbled upon the following problem that I have no clue how to solve.
I have two classes, let's call them library and book. Both are residing in their own .cpp files and have their own header files. Until now its pretty much standard. The problem I have is: The library class need a variable book (still easy), but book also needs a pointer back to library (here the problem kicks in). However, they are not inherited from each other or so, and it would be hard it that way.

so whole thing looks somewhat like this:

class library{
public:
vector<book*> books;
...
}

class book{
public:
library *position;
}

My g++ compiler keeps telling me that it does not know that either book or library have not been declared, depending on in which order I put the includes.

I would be very grateful for any suggestions on either how to fix the problem or make it more elegant.

Ralf
You can declare a class:
1
2
3
4
5
6
7
8
class book;//declaration

class library
{
   public:
      vector<book*> books;//recognizes book as valid type
   //...
};
1
2
3
4
5
6
7
class library;

class book
{
   public:
      library *position;
};
Last edited on
Which, BTW, is the right way to write the header file.

Header files should forward declare types when possible not only to avoid the circular dependency problem but also to help control compile times when you work on huge projects (the one I work on is upwards of a million lines of code
in thousands of source files).
Topic archived. No new replies allowed.