C++ Circular Dependency in Header Files
Is it possible to avoid circular dependency in the following header files without turning data member b1 in class A to a pointer/reference, and without relaxing the inline function requirement in class B?
A.h:
#ifndef A_H
#define A_H
#include <B.h> // Required, as data member b1 is not a pointer/reference
class A {
public:
B b1; // I want to keep this as as it is.
int m_a;
};
#endif
B.h:
#ifndef B_H
#define B_H
#include <A.h> // Required, as f() calls a member function of class A
class B {
public:
int f(A &a){return a.m_a;} // I want this to be an inline function.
};
#endif
...and let's say main.ccp is:
#include <iostream>
#include <A.h>
#include <B.h>
int main() {
A a;
B b;
std::cout << "Calling b.f(a): " << b.f(a) << std::endl;
return 0;
}
Solution 1:
You could use this:
A.h
#include <B.h>
#ifndef A_H
#define A_H
class A
{
public:
B b1;
int m_a;
};
#endif // A_H
B.h
#ifndef B_H
#define B_H
class A;
class B
{
public:
int f(A &a);
};
#include <A.h>
inline int B::f(A &a)
{
return a.m_a;
}
#endif // B_H
main.cpp
#include <iostream>
#include <A.h> // these could be in any order
#include <B.h>
int main()
{
A a;
B b;
std::cout << "Calling b.f(a): " << b.f(a) << std::endl;
return 0;
}