What are those types of pointers called and how do they work?

78 Views Asked by At

I did an hour of googling trying to understand the usage of pointers in this code to no avail.

#include <cstddef>

using namespace std;

class Node {
    public:
        int data;
    Node * next;
};

int main() {
    Node * head = NULL;
    Node * second = NULL;
    Node * third = NULL;

    head = new Node();
    second = new Node();
    third = new Node();

    head->data = 1;
    head->next = second;

    second-> data = 2;
    second-> next = third;

    third-> data = 3;
    third-> next = NULL;
}

I am confused about how these pointers are used.

Node * head = NULL;
    Node * second = NULL;
    Node * third = NULL;

    head = new Node();
    second = new Node();
    third = new Node();

Why does the pointer point to the constructor of the class?Shouldn't it point to a memory address? What is this particular technique of using pointers called? Thank you in advance!

2

There are 2 best solutions below

2
Vera F W C On BEST ANSWER

Ahh... These would be called "Node pointers", or "pointers to nodes." Their purpose is to point to Nodes. ;)

Snark aside, your understanding of pointers themselves seems okay: Pointers store the memory address of some piece of data.

In head = new Node(), you've misunderstood how the new keyword and constructor interact: new allocates memory for a new object, calls the class constructor, and returns the address of the newly created instance. In this case, then, head = new Node() creates a brand new Node object in the memory, and returns the address - which is then saved into head`.

It seems you might benefit from a good reference on C++, as a few comments have mentioned before. I can recommend Learn C++ if you aren't the type for books. You might find useful the introduction to pointers and the introduction to "dynamic memory allocation", which is all about new and it's counterpart delete.

0
Ross Douglas On

The pointer points to the constructor class because the constructor class returns a pointer to a new object. Essentially, new Node(); allocates a space in memory for a new node returns the memory address at the beginning. Thus, the line head = new Node(); initializes head. Without this, head->data = 1; would generate a segmentation fault since head does not reference any space in memory. Feel free to respond with any further questions