I have a problem which I think is related to forward declarations, but perhaps not.
Here is the relevant code:
A.h
#ifndef A_H_
#define A_H_
#include "B.h"
class A
{
private:
B b;
public:
A() : b(*this) {}
void bar() {}
};
#endif /*A_H_*/
B.h
#ifndef B_H_
#define B_H_
#include "A.h"
class A;
class B
{
private:
A& a;
public:
B(A& a) : a(a) {}
void foo() { /*a.bar();*/ } //doesn't compile
};
#endif /*B_H_*/
main.cpp
#include "A.h"
int main()
{
A a;
return 0;
}
The problem seems to be with the invocation of A::bar(). The program successfully compiles until I attempt to call this method at which point I get two errors:
error: invalid use of incomplete type ‘struct A’
error: forward declaration of ‘struct A’
I presume this is because A::bar() has yet to be defined or declared since both headers reference each other. However, I forward declared class A and am at a loss as to what else I need to do. I am new to C++, so please forgive me. I could not find the answer to this question anywhere else online. As always, thanks in advance!