Example of Circular Dependencies in C++
Implementation of circular dependencies in C/C++ can be a bit tricky, because any class or structure definition must be placed above its usage in the same file. A circular dependency between classes A and B will thus both require the definition of A to be placed above B, and the definition of B to be placed above A, which of course is impossible. A forward declaration trick is therefore needed to accomplish this.
The following example illustrates how this is done.
- File a.h:
- File b.h:
- File main.cpp:
Note that although a name (e.g. A) can be declared multiple times, such as in forward declarations, it can only be defined once (the One Definition Rule).
Read more about this topic: Circular Dependency
Famous quotes containing the word circular:
“A thing is called by a certain name because it instantiates a certain universal is obviously circular when particularized, but it looks imposing when left in this general form. And it looks imposing in this general form largely because of the inveterate philosophical habit of treating the shadows cast by words and sentences as if they were separately identifiable. Universals, like facts and propositions, are such shadows.”
—David Pears (b. 1921)