-5

I wrote the following code in java :

class node{
  int key;
  node left ,right;
  public node(int item ){
  key = item;
  left = right = NULL;
 }

it works fine in java but when i try to implement the same thing in c++ , it shows an error saying,"error: field 'left' has incomplete type 'node'". Can anyone explain how is this happening ? and what can i do to remove this error? i want to know how these two languages are implementing this.

jasmeet
  • 1
  • 1
  • 3
  • In C++, you must use pointer to achieve the same thing as the `node left, right;` you have in Java. E.g. `node * left, right;`. Btw, you should name your class `Node` and not `node`. – Dat Nguyen Jun 26 '17 at 05:38
  • 2
    @DatNguyen That declaration only declares `left` as a pointer. And the upper/lower case of the first character in the class name is up to personal preference or company style guides. – Some programmer dude Jun 26 '17 at 05:40
  • 7
    C++ is not Java. Please don't use Java as a model in writing C++ code. – PaulMcKenzie Jun 26 '17 at 05:40

1 Answers1

6

In Java, when you declare a variable of some object type, you really only declare it as a reference to the object. In C++ an object declared as

node left;

says that left is an actual instance of the node class. And to be able to define an instance the full definition of the class is needed.

Inside a class, when declaring member variables and functions, the class isn't actually fully defined yet, it doesn't happen until the closing }.

To declare a variable to be a reference you need to use the & character, like

node& left;

Or use pointers, as in

node* left;

Pointers are the most common when one needs to link to objects, because the semantics for references are such that once initialized a reference can not be changed to reference another object.

All of this, and much more, should be in any good beginners C++ book, which I recommend you find and read one.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621