C++ Programming Exercise: 1. A NumList class contains member variables int lengt
ID: 640843 • Letter: C
Question
C++ Programming Exercise:
1. A NumList class contains member variables int length and int *nums. When an object is constructed, length will be set to a positive value and nums will be set to a dynamically allocated array of size length. In each part below implement the class member as if defined outside the class declaration.
a. Define a constructor with one parameter representing the desired length. (If the parameter is < 1, set length to 1.) Set all elements to 0.
b. Define the copy constructor.
c. Define the destructor.
Can someone give me the code for only the constructor, copy constructor, and destructor?
Explanation / Answer
// constructor
NumList::NumList(int len){
if(len < 1){
len = 1;
}
length = len;
nums = new int[len];
for(int i = 0; i < len; ++i){
nums[i] = 0;
}
}
// copy constructor
NumList::NumList(NumList &l){
length = l.length;
nums = new int[length];
for(int i = 0; i < length; ++i){
nums[i] = l.nums[i];
}
}
// destructor
NumList::~NumList(){
delete[] nums;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.