Classes

Hi! I would like to ask how to create this to a header file and implement it on a cpp file?

This is a linked list code by the way.

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
36
37
38
39
40
41
42
43
struct Node
{
    int data;
    struct Node *next;
};

//insert a new node in an empty list
struct Node *insertInEmpty(struct Node *last, int new_data)
{
   // if last is not null then list is not empty, so return
   if (last != nullptr)
   return last;

   // allocate memory for node
   struct Node *temp = new Node;

   // Assign the data.
   temp -> data = new_data;
   last = temp;

   // Create the link.
   last->next = last;

   return last;
}

//insert new node at the beginning of the list
struct Node *insertAtBegin(struct Node *last, int new_data)
{
   //if list is empty then add the node by calling insertInEmpty
   if (last == nullptr)
   return insertInEmpty(last, new_data);

   //else create a new node
   struct Node *temp = new Node;

   //set new data to node
   temp -> data = new_data;
   temp -> next = last -> next;
   last -> next = temp;

   return last;
}
Note: C++ does not require the keyword "struct" when you use a typename.

A header must contain what the user needs to know.

How would you use your linked list? Something like this?
1
2
3
4
5
int main()
{
  Node* root = nullptr;
  root = insertAtBegin( root, 42 );
}

We need to know what the Node is. However, we create a mere pointer, so we don't need to know much. To know that it is a name of a struct is enough.

We need to know what the insertAtBegin is. That is what function declaration tells.

Hence:
1
2
3
4
5
6
7
8
struct Node; // forward declaration of struct
Node* insertAtBegin( Node *last, int new_data );

int main()
{
  Node* root = nullptr;
  root = insertAtBegin( root, 42 );
}

With those two lines (in header) we can write our main().

If you need to create an object, then you need definition of the type:
1
2
3
4
5
6
7
8
9
10
11
12
struct Node // definition
{
    int data;
    Node *next;
};

int main()
{
  Node local;
  Node* dynamic = new Node;
  delete dynamic;
}


The implementations go to (exactly one) source file.
Topic archived. No new replies allowed.