[ fromfile: classdeclarations.xml id: classdeclarations ]
the compiler needs to have some knowledge of each class before defining the other.
Example 2.12. src/circular/badegg/egg.h
[ . . . . ] #include "chicken.h" class Egg { public: Chicken* getParent(); }; [ . . . . ]
Example 2.13. src/circular/badegg/chicken.h
[ . . . . ] #include "egg.h" class Chicken { public: Egg* layEgg(); }; [ . . . . ]
The preprocessor does not permit circular dependencies such as these.
In this example, neither header file needed to include the other.
In each case, doing so created an unnecessarily strong dependency between header files.
Under the right conditions, C++ permits you to use a forward class declaration instead of #including
a particular header.
Example 2.14. src/circular/goodegg/egg.h
Classes that are declared but not defined can only be used as types for pointers or references, as long as they are not dereferenced in the file.
We define getParent()
in the source code module, egg.cpp
, shown in Example 2.15.
Notice that the .cpp
file can #include
both header files without causing a circular dependency between them.
The .cpp
file has a strong dependency on both headers, while the header files have no dependency on one another.
Example 2.15. src/circular/goodegg/egg.cpp
For further details, see Section C.2
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |