To break a circular dependency between classes, the traditional approach is to seperate declaration and definition and forward-declare a class where needed. However, forward declaration is not possible when two classes inheriting from the same base class depend on each other, as the compiler needs to see the declaration of methods to do inheritance.
Here's what it looks like.
// Base.hpp
class Base {
public:
virtual ~Base() = default;
void foo();
};
// DerivedA.hpp
#include "Base.hpp"
class DerivedB;
class DerivedA : public Base {
public:
void bar(DerivedB& b);
};
// DerivedB.hpp
#include "Base.hpp"
class DerivedA;
class DerivedB : public Base {
public:
void baz(DerivedA& a);
};
Then, when I try to implement DerivedA or DerivedB:
// DerivedA.cpp
#include "DerivedA.hpp"
#include "DerivedB.hpp" // ERROR: redeclaration of Base
void DerivedA::bar(DerivedB& b) {
b.foo();
}
I can't find any way out of this except for a large change in code structure. Is there a better way?