Search code examples
c++headerincludeforward-declaration

How to use instances of two classes in each others


Just as the title state; imagine I have those two header files:

// a.h
class A {
    A();
    B operator+(A);
}

and

// b.h
class B {
    B(A);
}

Is it somehow possible to make this work using includes/forward declares?

I've of course seen many related questions but they usually either have A and B contain instance of each other (which is obviously impossible) or can be fixed with pointers or references instead of object instances. However, I still want B's constructor to actually use a A instance, is that possible?


Solution

  • Is it somehow possible to make this work using includes/forward declares?

    It sure is.

    The declaration of a function only depends on declaration of the types of its argument and the return. They don't depend on the definitions.

    As such, neither class depend on the definition of the other but only on the declaration. So simply forward declare one before defining the other. B A::operator+ does depend on definition of B and B::B does depend on definition of A, so those must be defined in correct order. At least one of those has to be defined outside the definition of the class in order to satisfy the dependency requirements.

    • To define A:

      • Declare B
      • Define A
    • To define B:

      • Declare A
      • Define B
    • To define B A::operator+

      • Define A and B in any order
      • Define B A::operator+
    • To define B::B

      • Define A and B in any order
      • Define B::B

    An example:

    struct B;
    struct A {
        B operator+(A);
    };
    struct B {
        B(A){}
    };
    B A::operator+(A) {
        return {*this};
    }
    int main() {
        A a;
        B b = a+a;
    }