Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a class before defining it?

class Node
{
    string name;
    Node previous;
};

 Error: Node::previous uses "Node" which is being defined.

How can I get this to work in C++? It works in C#.

EDIT:

Why Node* previous works?

like image 287
Pratik Deoghare Avatar asked May 25 '10 13:05

Pratik Deoghare


2 Answers

Use pointers. Node* previous; would solve the problem.

As you're doing it now, you actually try to make your class infinitely large.

like image 181
M. Williams Avatar answered Oct 05 '22 13:10

M. Williams


Use a pointer or a reference.

For example:

Node* previous;

The only restriction is that a class cannot have an actual field of itself, likely for construction reason. Think about it, if every Box contains another Box inside it, how would you end up with a finite number of boxes?

If I'm not mistaken, C# only uses references for class types (as does Java), so you're using a reference there, just not seeing it.

like image 45
Uri Avatar answered Oct 05 '22 12:10

Uri