Reputation: 77
I am trying to create a structure that has to hold the data of the same struct type. Is this possible?
I can define a pointer to an object of the same type, but not the structure itself.
struct Node
{
vector<string> state;
struct Node *prev;
int id;
Node()
{
}
~Node()
{
}
};
This is possible. But I cannot define like below. The execution gives an error saying "incomplete type is not allowed".
struct Node
{
vector<string> state;
struct Node prev;
int id;
Node()
{
}
~Node()
{
}
};
Is this possible? If it is, what should I do to get rid of the error?
I have seen that this is possible in Java using classes,
public class Vertex implements Comparable{
public Pallet[] bins;
public int cost;
public Vertex parent;
}
Thank you
Upvotes: 1
Views: 663
Reputation: 180
No.
struct Node
{
vector<string> state;
struct Node prev;
int id;
Node()
{
}
~Node()
{
}
};
This code does not work because type Node does not know how much space to allocate for an object of type Node. The type is still in the process of being defined. Therefore, it does not yet know.
But, I can do it with a pointer!?
Yes. A pointer holds not an object, but the memory location of an object. The compiler is aware that Node is a data type, but it does not need to know how much to allocate as the allocation will be manually done later.
But, I can do it in Java!?
References in Java are NOT the same as C++ pointers (What is the difference between a pointer and a reference variable in Java? ). But, for many purposes, you can think of them as the same. Remember that when you create a member in a Java class, you are creating a reference. (How can a class have a member of its own type, isn't this infinite recursion?). A Java reference will refer (point) to the actual object. The member "parent" in your Java class is not the object itself but a reference to the object. The same way as "*prev" in you C++ class is not the object but points to the location of the object.
Upvotes: 1