imeluntuk imeluntuk - 1 month ago 14
C++ Question

C++ error : field has incomplete type - declaring it's own class object

I'm new to C++ programming. Here is my code :

#ifndef NODE_H
#define NODE_H

class Node
virtual ~Node();
Node(const Node& other);

int getValue() { return value; }
void setValue(int val) { value = val; }
Node getPrev() { return prev; }
void setPrev(Node val) { prev = val; }
Node getNext() { return next; }
void setNext(Node val) { next = val; }

int value; //!< Member variable "value"
Node prev; //!< Member variable "prev"
Node next; //!< Member variable "next"

#endif // NODE_H

It says :

error field 'prev' has incomplete type
error field 'next' has incomplete type

If I use pointer/reference, the program works fine. Why is this mechanism exist? How to do it without pointer/reference?
Thanks for your response.


The class isn't fully defined until that closing brace. Before that you can't define objects of the class. A major reason is that the size of the object isn't known yet, so the compiler doesn't know how much memory to allocate for the member variables.

When you use pointers or references to the class, the compiler will know how much memory a pointer or reference takes up, as it's unrelated to the size of the actual class.