It is clear that in the void additem(int d) method we can access the fields of the link structure via a pointer to the structure object as follows:

 newlink->data = d; newlink->next = first; 

Then how do we access these very fields of the structure through the current pointer in the class method, if this pointer does not point to the structure from the very beginning:

 link* current = first; while (current) { cout << current->data << endl; current = current->next; } 

???

Code:

 class linklist { struct link { int data; link* next; }; link* first; public: linklist() : first(NULL) { } void additem(int d); void display(); }; void linklist::additem(int d) { link* newlink = new link; newlink->data = d; newlink->next = first; first = newlink; } void linklist::display() { link* current = first; while (current) { cout << current->data << endl; current = current->next; } } int main() { setlocale(LC_ALL, "rus"); linklist li; li.additem(23); li.additem(9); li.additem(11); li.additem(0); li.display(); cout << endl; system("pause"); return 0; } 
  • What does it mean "does not indicate structure from the very beginning"? You have the current pointer inside the method that refers to the first initialized in the constructor. - margosh
  • current - in your case, i is a loop variable. You have a cycle to the next, while the next exists. In principle, for (i=0;i<n;i++) can be written as i=0 (first) while (i< n) { i=i+1} instead of i=i+1 you have current =current->next; - nick_n_a
  • and how do we access the structure data through the current pointer, if current does not point to the structure object? - Artem Aleksandrovich
  • @Artem Aleksandrovich: Your statement "current does not indicate a structure object" is incorrect. From the fact that you will repeat it, it will not be true. Current you point to the object of your structure. - AnT

1 answer 1

The current pointer is found inside the method, and, as is known, an implicit this pointer is passed to the object (unless of course it is a static method).

According to the above code, you get a list in which the first pointer points to the last object added to the list:

 NULL <-- |el1.next| <-- |el2.next| <-- first 
  1. In the case where there are no elements, display () will not output anything, since the condition is checked

    while (current)

  2. After the first item is added, first points to this item in the list and the next item field to NULL. Accordingly, in the display () function, by assigning the current pointer the value of the pointer first , you can refer to the fields of the structure that is a list item.

UPD:

and how do we access the structure data through the current pointer, if current does not point to the structure object?

The current inside the display () method is assigned the value of the first pointer, which just points to the structure inside the linklist class.