0
#include "passenger.h"
class node
{
public:
    passenger dataItem;
    node nextNode;
};

Why do i get a incomplete type not allowed error when trying to create a varaible whose type is the class it resides in?

Robert Spratlin
  • 305
  • 3
  • 5
  • 8

1 Answers1

5

Try to follow the compilers though process.

What is sizeof(node).

To fix, consider using a pointer to node.

class node
{
public:
    passenger dataItem;
    node * nextNode;
};

After seeing your code, it looks like you are from Java/C# background, which means infact, that you do actually want pointers, to emulate references from those languages.

Remember that objects are references types in those languages, while they are value types in C/C++. The difference is that node nextNode POINTS TO the next node in Java/C# while it IS the object itself in the case of C/C++.

Edit: Your error is caused due to the fact that when you define the member variable nextNode, you are still in the middle of defining node, thus it is incomplete. node* will work, since pointers only need a forward declaration, and are fine with incomplete types.

Similarly, it works in Java/C#, because every variable in those languages (minus C# structs and Java primitives) are just pointers with some make up.

Edit: Please read up on pointers in C++ and new/delete I expect you are in for a crash or two soon.. :(. Also take a look at What are the barriers to understanding pointers and what can be done to overcome them? to start.

To summarize, to assign a pointer you do the following.

node a;
node b;

a.nextNode = &b; //& operator returns the address of its operand, here b
Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • thats not really the issue, VS 2010 draws a red line under nextNode and says "Error: incomplete type is not allowed". I have yet to compile because of the error – Robert Spratlin Feb 25 '13 at 01:51
  • 1
    Its incomplete because it is incomplete.. the `};` comes after your definition of the member variable. – Karthik T Feb 25 '13 at 01:52