David Sánchez
David Sánchez

Reputation: 624

Class definition error - Field next has incomplete type

I have a very small question. Why is this code throwing the following error?

Field next has incomplete type.

I am declaring a class, which has an attribute

#ifndef NODE_H
#define NODE_H

class Node
{
public:

    int d;

    Node(int d){
        this->d = d;
    }

    Node next = 0;

};

#endif // NODE_H

BUT!!! If i change for a pointer works:

Node *next;

Is interesting since this is from the book cracking the coding interview.

Can someone show some light on me? (A most likely make me fell ashame :D)

Thanks in advance

I did my homework and I couldnt find the solution either here or here

Upvotes: 4

Views: 10556

Answers (2)

dwcanillas
dwcanillas

Reputation: 3651

That's not there error I get, that is just the intellisense error.

However, Node has not been fully defined yet, so the compiler doesn't know what kind of object it is, or how much memory it takes up.

Regardless, I don't think that is the problem. Declaring a Node object inside the Node class itself, would create a recursive dependency, and again, the compiler would not be able to resolve how much memory one Node would need.

Since a pointer is just a memory address and has a fixed size, the compiler is happy and it can be declared.

Upvotes: 1

James Adkison
James Adkison

Reputation: 9602

You're declaring a class of type Node but that declaration is not complete until it reaches the closing brace and semi-colon.

class Foo
{
}; // Class declaration is complete now

However the following cannot work, see code comment.

class Node
{
public:

    int d;

    Node(int d){
        this->d = d;
    }

    // This is a instance of a class and as such the compiler needs to
    // know the full definition of the class. HOWEVER, this is the class
    // that's being defined (i.e., it isn't fully defined yet!)
    Node next = 0; // Assigning 0 here doesn't make any sense

};

BUT!!! If i change for a pointer works

A pointer does not require a complete type (i.e., doesn't require the full definition) therefore it's fine to use while still defining the Node class.

Upvotes: 10

Related Questions