Reputation: 1402
Despite many questions similar to this I'm unable to find one that can answer such a simple query - however due to the volume you'll have to forgive me if I have missed it.
Within the following code, the following error is produced (using G++): 'error: field 'CompoundField' has incomplete type'
:
class SimpleClass;
class CompoundClass;
class CompoundClass{
public:
SimpleClass CompoundField;
};
class SimpleClass{
public:
unsigned int SimpleField;
};
int main(){
CompoundClass obj;
obj.CompoundField.SimpleField=5;
return 0;
}
Why is this when both classes have been forward-declared? A straight forward solution is to just move the CompoundClass
to after the SimpleClass
, or make CompoundField
a pointer to SimpleClass
but that doesn't help explain the underlying issue here.
To be more precise, other answers indicate this is due to the compiler not knowing the size of the child class (i.e. SimpleClass
), why is this when the size of SimpleClass
could be found with relative ease?
Upvotes: 0
Views: 111
Reputation: 59987
The compiler sees this
class SimpleClass;
class CompoundClass;
class CompoundClass{
public:
SimpleClass CompoundField;
};
It needs to figure out how much memory a CompoundClass
requires (has not got a clue aboutSimpleClass
memory requirement).
As it does not know how many ints, strings etc.. to make space for - it throws its hands up.
But if you did
class SimpleClass;
class CompoundClass;
class CompoundClass{
public:
SimpleClass *CompoundField;
};
Then it would know - just need a pointer (void *
will suffice for all eventualities!)
Upvotes: 4