I'm trying to create class Object before defining class. Here is the example.
class A;
class B;
class A{
public:
void fun(B obj){
}
};
class B{ };
int main(){
return 0;
}
Here is the Error List:
In member function 'void A::fun(B)':
6 13 [Error] 'obj' has incomplete type
2 7 [Error] forward declaration of 'class B'
Any Solution? I already Searched about it, but failed to solve this.. Thanks in Advance.
Provide
A::fun()
's definition out-of-line, afterB
has been fully declared :The definition wil typically go into a .cpp file, where you'd include
B.h
to have its complete declaration.Also, please don't
using namespace std;
.At this point:
the compiler needs to know what
B
is. That is, how big it is, what types its members have, what constructors are defined, etc. Otherwise, it can't generate the code you're asking it to.You can work around this by:
B
beforeA
, orA::fun
inline, and move the definition afterB
has also been definedpass
B obj
by pointer or reference - because pointers and references are all the same size, and neither invoke constructors you haven't declared yet, this works, but ... you still can't do anything with theB
instance infun
untilB
has been defined.So, the current code will compile, but it will break again if
fun
does anything more than pointer arithmetic.In this function definition,
you're telling the compiler that you are going to pass an instance of
B
on the stack tofun
. The compiler therefore needs to know the definition ofB
so that it knows how much stack space to allocate. At this point in the code, you have only declared thatB
exists. You have not provided it a definition ofB
, so it can't know how much memory is required.[Edited to fix the declaration/definition misstatement]