I have a question regarding the use of new within my class definition: when I call delete in main, does it free all memory allocated for each node and for list or just list?
Code:
//linked_list.h
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include <iostream>
#include <string>
class Linked_list {
public:
Linked_list();
Linked_list *startnode(std::string data, Linked_list *node);
Linked_list *addnode(std::string data, Linked_list *node);
Linked_list *delnode(Linked_list *node);
void display(Linked_list *a_list) const;
private:
Linked_list *link;
std::string data;
};
#endif
Code:
// Linked_list.cpp
#include "Linked_list.h"
using namespace std;
Linked_list::Linked_list() : link(0), data(" ") {}
Linked_list *Linked_list::startnode(std::string data, Linked_list *node)
{
node->data = data;
node->link = 0;
return node;
}
Linked_list *Linked_list::addnode(std::string data, Linked_list *node)
{
Linked_list *next = new Linked_list;
next->data = data;
next->link = node;
return next;
}
Linked_list *Linked_list::delnode(Linked_list *node)
{
Linked_list *head = node;
head = head->link;
node->link = 0;
return head;
}
void Linked_list::display(Linked_list *a_list) const
{
while(a_list != 0)
{
cout << a_list->data << endl;
a_list = a_list->link;
}
}
Code:
#include "Linked_list.h"
using namespace std;
int main(int argc, char *argv[])
{
Linked_list *a_list = new Linked_list;
string word = "Jesus";
a_list = a_list->startnode(word, a_list);
word = "Glory to God!";
a_list = a_list->addnode(word, a_list);
a_list->display(a_list);
delete a_list;
return 0;
}
Thank you in advance for your kind support of my question.