"New"

Hi I am learning about linked list and there is a part of the code that I do not understand for example:


1
2
3
       ListNode* newnode = new ListNode();
        newnode->data = x;
        newnode->next = front;  // Points to rest of list 


I dont understand what "new" and "->" does. Can someone please explain to me? thank you for your help
new creates the object of type ListNode (->enough space) on the heap and calls the constructor.

-> is the operator to access the members according to the pointer in newnode which was previously created on the heap.

In other words: It takes the address and adds the offset of the (data) member. The result is the actual address to read from or (like above) write to
If ListNode were an object, you'd access its members using the dot notation:
1
2
3
ListNode newnode;
newnode.data = x;
newnode.next = front;


However, ListNode is a pointer to an object (returned by new, required by the linked list structure). This means that to access its members, we first need to dereference it. We could do it like this:
1
2
3
ListNode* newnode = new ListNode();
(*newnode).data = x;
(*newnode).next = front;

Since that's a bit messy, C(++) has the arrow notation, which is a combined dereference-and-dot operator:
1
2
3
ListNode* newnode = new ListNode();
newnode->data = x;
newnode->next = front;


The second and third code fragments are the exact same, conceptually. It looks different, but it works exactly the same way.
Topic archived. No new replies allowed.