In: Computer Science
#ifndef CONTAINER_H
#define CONTAINER_H
using namespace std;
class container {
public:
// CONSTRUCTOR
container();
~container();
container(const container& c);
container& operator=(const container& c)
// MEMBER FUNCTIONS
bool lookup(const int& target);
void remove(const int& target);
void add(const int& target); private:
struct node{
int key;
node *next;
};
node* head;
node* tail;
};
#endif
For a linked list based implementation of a container class shown above, implement the constructor, copy constructor, destructor and copy assignment functions.
Here is the completed code for these four methods. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//default constructor implementation
container::container(){
//setting head and tail to NULL
head=tail=NULL;
}
//destructor implementation
container::~container(){
//looping until head is NULL
while(head!=NULL){
//fetching and storing next of head
node* nxt=head->next;
//removing head
delete head;
//setting nxt as new head
head=nxt;
}
//setting tail to NULL
tail=NULL;
}
//copy constructor implementation
container::container(const container& c){
//initializing head and tail to NULL
head=tail=NULL;
//taking reference to head of c
node* other=c.head;
//looping until other is NULL
while(other!=NULL){
//using add() method, adding other->key to this list
add(other->key);
//moving to next node
other=other->next;
}
}
//copy assignment function implementation
container& container::operator=(const container& c){
//repeating the same as previous method
head=tail=NULL;
node* other=c.head;
while(other!=NULL){
add(other->key);
other=other->next;
}
//returning a reference to current object.
return *this;
}