Reputation: 1044
Suppose I have:
class B;
class A{
private:
B *b;
public:
bar(){ b->foo()};
foo();
}
class B{
private:
A *a;
public:
bar(){ a->foo();}
foo();
}
When compiled this file gives an
error "invalid use of incomplete type struct B",
even after I have forward declared the class B. As far as I understand it is because when I am calling the function foo()
on b
, the compiler still doesn't know that such a function exists. How can I solve this problem?
Upvotes: 1
Views: 273
Reputation: 409216
The error is because you try to use a method from B
in A::bar
. While class B
has been declared, it has not been defined.
Like the others say, you should separate the definition and the implementation, and it will work.
Upvotes: 1
Reputation: 258618
The forward declaration provides no implementation details. B
is not known to A
, other than the fact that it exists.
To solve this, separate your declaration from the implementation.
You're also missing return types for the methods.
File A.h:
class B;
class A{
private:
B *b;
public:
void bar();
void foo();
};
File A.cpp:
#include "A.h"
#include "B.h"
void A::bar(){
b->foo();
}
File B.h:
class A;
class B{
private:
A *a;
public:
void bar();
void foo();
};
File B.cpp:
#include "B.h"
#include "A.h"
void B::bar(){
a->foo();
}
Upvotes: 10