Sample Output Program to dynamically Allocates an array of integers. Enter the s
ID: 3611660 • Letter: S
Question
Sample Output
Program to dynamically Allocates an array of integers.
Enter the size of the array: 4
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
The elements of the array are:
1 2 3 4
Enter the elements in the array after reallocation:
Enter a value: 5
Enter a value: 6
Enter a value: 7
Enter a value: 8
1 2 3 4 5 6 78
Sample Output
Program to dynamically Allocates an array of integers.
Enter the size of the array: 4
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
The elements of the array are:
1 2 3 4
Enter the elements in the array after reallocation:
Enter a value: 5
Enter a value: 6
Enter a value: 7
Enter a value: 8
1 2 3 4 5 6 78
Explanation / Answer
class A { size_t mSize; int& mArray; public: // Simpleconstructor/destructor are obvious. A() {mSize=0;mArray = NULL;} A(size_t s) {mSize=s;mArray = new int[mSize];} ~A() {delete [] mArray;} // Copyconstructor needs more work A(A const©) { // Alwayscreate the copy first. // Only setthe member variables after the copy hassucceeded // NB NEVER delete your data before the copyworked. int* data =new int[copy.mSize]; // Don'tneed to worry about copying integers. // But ifthe object has a copy constructor then // it wouldalso need to worry about throws from the copyconstructor. std::copy(©.mArray[0],©.mArray[c.mSize],data); delete []mArray; mArray =data; mSize = copy.mSize; } // Defineassignment operator in terms of the copyconstructor A& operator=(Aconst& copy) { if (this ==©) { // Ignore assignment to self. return; } // Use thestandard copy and swap idiom A tmp(copy); tmp.swap(*this); } void swap(A&s) throws () { std::swap(this.mArray,s.mArray); std::swap(this.mSize ,s.mSize); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.