|
Circular dependencies is a situation which occurs in object oriented programming when two or more objects point towards each other in a circular fashion. Circular dependencies are usually used to implement callback functionality in programs. However, occurrences of circular dependencies should normally be limited, since they make the resulting object-models unclear and unstructured, and are hence considered a bad programming habit. Circular dependencies will also prevent automatic garbage collectors from deallocating objects.
Circular dependencies in C++ Implementation of circular dependencies in C/C++ can be a bit tricky, due to the requirement that any class or structure definition must be placed above their 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. Circular dependencies in C/C++ are implemented by using forward declarations. The following example illustrates how this is done. class B; //forward declaration class A ; class A; //forward declaration class B ; void main() Self-reference example Following is another example of forward declaration, which might be useful if the application needs a self-sustaining array of objects which is able to add and remove objects from itself during run-time: The static variables first and last have to be defined, because their declaration does not reserve memory space for them. Note: static variables do not change from object to object and stay the same for this given class. A first, A: A() A: ~A | ||||||||
|
| |||||||||
![]() |
|
| |