In my project, there's no way to re-arrange the classes in order for the error to go away. Is there a way to bypass this error?
You are describing a circular dependency. X
depends on Y
and Y
depends on X
. Such dependency is unsolvable. If you can remove a dependency on one class from another class, then it may be possible to re-order the definitions so that all dependencies are satisfied. Sometimes dependency can be removed by introducing indirection.
Note that just because one class definition (A
) depends on declaration of another class (B
), that doesn't necessarily mean that it depends on the definition of that class. You can have one class depend on the definition of another class, while still having the dependee class depend on the declaration of the depender.
Furthermore, just because definition of a member function (A::A
) depends on definition of another class (B
), that doesn't necessarily mean that the class (A
) has that same dependency. This is because it is not necessary to define member functions within the class definition.
For example, your example class A
does not depend on the definition of B
. As such, A
can be defined before B
:
// declaration of B
// not a definition
class B;
// definition of A
class A{
public:
B* b; // depends on declaration of B
// does not depend on the definition
A();
};
// definition of B
class B{
public:
B(){
}
};
// definition of A::A
// does depend on definition of B
A::A() {
b = new B();
}