nested structure pointers

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(structure) 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 don't see how you can make a new object(structure) of type Link and just change the last parameter ? I would have expected simply a : "head = new Link;", and then initialization of the members of struct Link. Can someone please explain it to me ??? Please??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 // Stack3.h
#ifndef STACK3.H
#define STACK3.H

class Stack {
 struct Link {
  void* data;
  Link* next;
  Link(void* dat, Link* nxt);
  ~Link();
}* head;

public:
 Stack();
 ~Stack();
 void push(void* dat);
 void* peek();
 void* pop();
};
#endif // STACK3.H 





Implementation:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 // Stack3.cpp
#include "Stack3.h"
#include "../require.h"
using namespace std;

Stack::Link::Link(void* dat, Link* nxt) {
 data = dat;
 next = nxt;
}

Stack::Link::~Link() {}

Stack::Stack() { head=0;}

void Stack::push(void* dat) {
head = new Link(dat, head);
}

void* Stack::peek() {
require(head != 0, "stack empty");
return head -> data;
}

void* Stack::pop() {
 if/head == =) return 0;
 void* result = head -> data;
 Link* oldHead = head;
 head = head -> next;
 delete oldHead;
 return result;
}

Stack::~Stack() {
require(head == 0,"stack not empty");
}

closed account (D80DSL3A)
Duplicate thread: http://www.cplusplus.com/forum/beginner/53172/
Please see your responses there.
Last edited on
Topic archived. No new replies allowed.