Reputation: 47
I have a code like this where i cannot put "struct node" above "struct mnode"
So i declared it on the top, as shown below.
But the compiler says the field n has incomplete type.
How to correctly declare a struct on the top??
struct node;
struct mnode{
int j;
node n;
};
struct node{
int k;
};
Upvotes: 1
Views: 113
Reputation: 11028
The compiler complains because it needs to know a few things about mnode
for which it needs more information about node
. First, it needs to know the size of a mnode
object in order to be able to construct it, but for that it needs to know the size of a node
. It also needs to know how to generate the following functions:
And for that it needs the corresponding functions in node
. I may be forgetting something else, but you can see that it needs the full definition of node
for quite a lot of things. So no, an advance declaration will not do.
If you cannot provide the full definition of node
for whatever reason, you can resort to changing the type of n
to, for instance, a node*
. The compiler has all that information for a pointer, so no problem there.
Upvotes: 1
Reputation: 14159
That's because node
is ... well incomplete. You cannot have fields of incomplete types in a struct/class definition. But you can have a pointer to node because the size of a pointer is known:
struct node;
struct mnode{
int j;
node* n;
};
struct node{
int k;
};
Upvotes: 1
Reputation: 258578
For a class-type class member, you need a definition. A declaration won't do. So in this case, the full definition of node
has to come before mnode
.
Forward declarations only work when the full definition isn't required - pointer or reference members, return types or method parameters.
Upvotes: 5