Please code in C++!! Consider the implementation of the List class using dynamic
ID: 3882753 • Letter: P
Question
Please code in C++!!
Consider the implementation of the List class using dynamic arrays (attached to the quiz description). Add a member function called clone() to the List class that returns an object of class 'List' itself. List clone(){ } The clone function should basically create a new List object, copy the contents of the original integerList object on which the function is called to the new List and return the clone to the main function. You should not create any other function to do this cloning and just make use of one or more of the existing functions in the current version of the List class as posted in the Lecture code. You should be able to print the contents of the cloned list by calling the print() member function on the cloned List object. If 'integerList' is the name of the original object of class List created in your main function, the clone() should be called as follows. The call to the print() function should follow next List cloneList = integerList.clone(): cloneList.print();Explanation / Answer
#include<iostream>
using namespace std;
class List {
private:
int count;
int *array;
int size;
public:
List(int a){
size = a;
array = new int[a];
count = 0;
}
int getSize(){
return size;
}
void add( int b){
if (count < size){
array[count] = b;
count++;
}
else {
int *p;
p = array;
array = new int[size * 2];
for (int i = 0; i<size; i++)
array[i] = *(p+i);
array[count] = b;
count++;
size = 2 * size;
}
}
int get(int index){
if (index < count)
return array[index];
else
return -1;
}
void print(){
for (int i = 0; i<count; i++)
cout << array[i] << " ";
cout << endl;
}
List clone(){
List *lt = new List(size);
for (int i = 0; i<count; i++){
lt->add(get(i));
}
return *lt;
}
};
int main(){
List lt(5);
lt.add(2);
lt.add(3);
lt.add(1);
List lt2 = lt.clone();
lt2.print();
return 0;
}