I am working my way through "thinking in c++" volume 1, and have come across something I do not think I understand completely:
In the implementation of the member function push() below, there is this line of code:head = new Link(dat, head);
I understand that it is allocating space on the heap for a new object of type Link. As far as I understand, "head" is a pointer to Link, so that this line of code would assign the address of the new Link object to "head". What I don't really understand is what is happening inside the parenthesis: "new Link(dat, head)". I would have expected simply a : "head = new Link;". I understand that it is assignment and intitialization simultaneously of some sort, but "head" is already initialized. Isn't it, and "dat" too? Can someone please explain it to me ??? Please??
Jes.. f...... christ. Do you think I formulate this question so that you can tell me what I already know ? The constructor function is : Link(void* dat, Link* nxt); , which doesn't match "Link(dat, head)".
So I am asking what is "head" doing in that initialization? "head" is set as a pointer to the Link structure, and next points to the next stored data item. If you cannot explain me yourself please do not refer to some generic source, as I am in that case more likely to understand this better than you anyway. Please, an administrator or something maybe??
Over-reacting like that will drive away other responders too.
That said, the code line is sensible.
head points to the 1st link in the stack (top of stack).
When a new link is pushed onto the stack it becomes the new 1st link so head needs to point to this new one, with next pointing to the old head link (now the 2nd one on the stack).
The constructor assigns new Link->next = head, then head is reassigned to point to the new link.
Without this constructor you would need to do this instead:
1 2 3 4
Link* temp = new Link;
temp->data = dat;
temp->next = head;
head = temp;
Thank you :-)
So in that line : head = new Link(dat, head);, "next" is assigned the new location that "head" points to, which is then assigned to the "new head" pointer ?
Would it then for readability be an idea to create for example head1, head2 etc.. , and then delete them when they had been used ?
You're welcome.
next is actually assigned the current value of head (the value passed to the constructor). new then returns a memory address (of the newly allocated Link) which is assigned to head. This is the new value for head.
There is no need for 2 head variables. Here's a similar situation involving an integer variable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// take a value n then return a value one greater
int addOne(int n)
{
int y = n;
return y+1;
}
int main()
{
int x = 3;
x = addOne(x);// function returns the number 4
cout << "x = " << x;// x now = 4
return 0;
}