1

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

rsvar67
  • 77
  • 8
  • 2
    The member of same type would contain a member of same type which contains a member of same type, wouldn't it? Where would that end in your opinion? – Yunnosch Apr 06 '19 at 22:05
  • 1
    Possible duplicate of ["Incomplete type" in class which has a member of the same type of the class itself](https://stackoverflow.com/questions/6349822/incomplete-type-in-class-which-has-a-member-of-the-same-type-of-the-class-itse) – kmdreko Apr 06 '19 at 22:13
  • @Yunnosch I got the point, but I saw that it is possible in Java with Classes. Please see the updated question. – rsvar67 Apr 06 '19 at 22:15

1 Answers1

1

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.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
user10447655
  • 180
  • 2
  • 10