Post by Zikun Xuif class A contain a member which is class B,
class B contain a member which is class A,
then A.h will include B.h
B.h will include A.h. thus it pose a mutual inclusion.
But mutual inclusion should be not allowed.
How can we solve this problem?
You can often get away with forward declaring one of the classes.
For example:
// book.h
class Library;
class Book {
Library *library;
};
This will work if you only have references or pointers to the class you
are forward declaring. In this example, the compiler only needs to know
that a Library class will exist, but not how large it is or what members
it has. Thus you don't actually need to include library.h in book.h.
If, however, the compiler does need to know the size of the other class
(for example, because there is an instance variable of that type), you
do need to provide the definition of the class.
This would not work in the following case:
// book.h
class Library;
class Book {
Library library;
};
Because the compiler would have to know how much memory the Library
instance requires before it can determine how much memory a Book requires.
--
Jeremy Roman
Student, Computer Science
University of Waterloo