a part of my program basically boils down to the code below which won't compile due to circular dependency. I know there are previous discussions about this topic, but none of the previous solutions (at least none that I can find) resolves my situation:
A.h
#ifndef A_H
#define A_H
#include <iostream>
#include "B.h"
class A
{
public:
typedef struct a_struct
{
int x;
int y;
}a_struct_t;
void print_something() { std::cout << "Hello world" << std::endl; }
private:
typedef struct another_struct
{
int x;
a_struct_t a_struct;
}another_struct_t;
friend void B::b_func1();
};
#endif
B.h
#ifndef B_H
#define B_H
#include "A.h"
class B
{
public:
void b_func1();
A::a_struct_t b_func2();
};
#endif
B.cpp
#include "B.h"
void B::b_func()
{
A::another_struct_t another_struct;
// Do something with another_struct;
}
A::a_struct_t B::b_func2()
{
A::a_struct_t a_struct;
return a_struct;
}
try.cpp
#include "A.h"
int main()
{
A a_object;
a_object.print_something();
return 0;
}
The issue is class A can't friend just void B::b_func1()
in A.h without #include "B.h"
and have class B be completely defined, but class B also can't use A::a_struct_t
in B.h
without #include "A.h"
and have class A
be completely defined. I've tried forward declaring class A
in B.h
, but I still can't use A::a_struct_t
in B.h
because class A
is an incomplete type.
I can move a_struct_t to class B
which works, but it really belongs in class A
. Also I can friend entire class B
and not #include "B.h"
in A.h which also works, but ideally I'd like to just friend void B::b_func1()
instead of the entire class B
. Is there a way to make this work? Thanks in advance,
P.S. - I've read about the forward declaration that was the top comment in the thread titled "Resolve build errors due to circular dependency amongst classes". That unfortunately doesn't work in my case, at least I've not been able to apply forward declaration in a way to rid of the error: invalid use of incomplete type 'class xxx'