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, after B
has been fully declared :
#include <iostream>
class A;
class B;
class A {
public:
void fun(B obj);
};
class B{ };
void A::fun(B obj) {}
int main() {
return 0;
}
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:
void fun(B obj) {
}
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:
- defining (not declaring)
B
before A
, or
- only declare
A::fun
inline, and move the definition after B
has also been defined
pass 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 the B
instance in fun
until B
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,
void fun(B obj){
}
you're telling the compiler that you are going to pass an instance of B
on the stack to fun
. The compiler therefore needs to know the definition of B
so that it knows how much stack space to allocate. At this point in the code, you have only declared that B
exists. You have not provided it a definition of B
, so it can't know how much memory is required.
[Edited to fix the declaration/definition misstatement]