2

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

#ifndef NODE_H
#define NODE_H    

class Node
{
    public:
        Node();
        Node(int);
        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; }

    private:
        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.

imeluntuk
  • 335
  • 1
  • 3
  • 15

1 Answers1

7

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.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550