For example there are classes A and B. A uses B's methods and vice versa. So, what is usually done is passing a pointer to an object of the other class in the constructor.
But what if they use each other – how should I pass B to A if B is not yet constructed? Ok, I wrote setter for A and call it after both are created. Now I don't use any B's code in A constructor, but it may change. What should I do then?
class A;
class B;
// A uses B
class A {
B* b;
public:
A() {
// potentially calls b's methods
}
void setB(B* b) { this->b = b; }
}
// B uses A
class B {
A* a;
public:
B(A* a) : a(a) {
// potentially calls a's methods
}
}
int main() {
A a;
B b(&a);
a.setB(&b); // ugly, but no alternative?
// Other classes use a and b
return 0;
}