So I have a class A, where I want to call some class B functions. So I include "b.h". But, in class B, I want to call a class A function. If I include "a.h", it ends up in an infinite loop, right? What can I do about it?
You cannot have two classes directly contain objects of the other type, since otherwise you'd need infinite space for the object (since foo has a bar that has a foo that has a bar that etc.) Notice that the two headers don't include each other.
It violates One Definition Rule.
Yes, but only if the two classes have the same name.
Put only member function declarations in header (.h) files, and put member function definitions in implementation (.cpp) files. Then your header files do not need to include each other, and you can include both headers in either implementation file.
For cases when you need to reference the other class in member signatures as well, you can use a forward declaration:
class A;
This lets you use pointer and reference types (A*
and A&
), though not A
itself. It also doesn't let you call members.
Example:
// a.h struct B; // forward declaration struct A { void foo(B* b); // pointers and references to forward-declared classes are ok }; // b.h struct A; // forward declaration struct B { void bar(A& a); // pointers and references to forward-declared classes are ok }; // a.cpp #include "a.h" #include "b.h" void A::foo(B* b) { b->bar(*this); // full declaration of B visible, ok to call members now } // b.cpp #include "a.h" #include "b.h" void B::bar(A& a) { a.foo(this); // full declaration of A visible, ok to call members now }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With