Circular Dependency - Example of Circular Dependencies in C++

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:
#ifndef A_H #define A_H class B; //forward declaration class A { public: B* b; }; #endif //A_H
  • File b.h:
#ifndef B_H #define B_H class A; //forward declaration class B { public: A* a; }; #endif //B_H
  • File main.cpp:
#include "a.h" #include "b.h" int main { A a; B b; a.b = &b; b.a = &a; }

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:

    If one doubts whether Grecian valor and patriotism are not a fiction of the poets, he may go to Athens and see still upon the walls of the temple of Minerva the circular marks made by the shields taken from the enemy in the Persian war, which were suspended there. We have not far to seek for living and unquestionable evidence. The very dust takes shape and confirms some story which we had read.
    Henry David Thoreau (1817–1862)