-3
class node{
    public:
    int data;
    node* next;
    node(int val){
       data=val;
       next=NULL;
    }
};

For this class, the object creation statement is node* n=new node(5);

Why do we need to add the * after node? What will happen if I write node n=new node(5)?

Are they both the same?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    This is really something any decent text-book, tutorial or class should have taught you. If not then you should consider using some other book, tutorial or class. [Here's a list of decent books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Some programmer dude Jan 02 '21 at 07:51
  • 2
    *"What will happen if i write `node n=new node(5)`?"* -- try it and see. – JaMiT Jan 02 '21 at 08:03

1 Answers1

1

Why do we need to add the * after node?

new returns a pointer to the memory that was allocated, in this case a node instance, so you need a (node*) pointer variable to receive the returned memory address (of the node instance).

What will happen if I write node n=new node(5)?

The code will fail to compile, since n is not a (node*) pointer.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770