Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

....................................Dynamic Arrays, Deep Copies, Memory Leaks...

ID: 3552794 • Letter: #

Question

....................................Dynamic Arrays, Deep Copies, Memory Leaks......................

.

Complete the following class by writing the bodies of the functions. Write some driver code to test all

features of the class DynamicDouble.


class DynamicDouble {

friend ostream& operator<<(ostream& cout, const DynamicDouble& right);

/*outputs the array of doubles*/

public:

DynamicDouble();

/*default constructor that allocates memory for one double value and sets that value to 0, size = 1*/

DynamicDouble(int n);

/*defined constructor that allocates memory for n double values and sets them all to 0, size = n*/

DynamicDouble(const DynamicDouble &copy);

/*copy constructor that performs a deep copy*/

void PushBack(double d);

/*adds d to the end of the data array. First increase size by 1, reallocate memory for the new array,

copy over old items from old array, free memory of old array, add d to the end of old data*/


private:

double *data;

int size;

};

Explanation / Answer

#include <iostream>


using namespace std;


class DynamicDouble {

friend ostream& operator<<(ostream& cout, const DynamicDouble& right);

/*outputs the array of doubles*/

public:


void print()

{

for(int i=0;i<size;++i)

{

cout<<" "<<data[i];

}

}

DynamicDouble();

/*default constructor that allocates memory for one double value and sets that value to 0, size = 1*/


DynamicDouble(int n)/*defined constructor that allocates memory for n double values and sets them all to 0, size = n*/

{

size=0;

data = NULL;

while(n--)

{

PushBack(0.0);

}

}


DynamicDouble(const DynamicDouble &copy);

/*copy constructor that performs a deep copy*/


void PushBack(double d)

/*adds d to the end of the data array. First increase size by 1, reallocate memory for the new array,

copy over old items from old array, free memory of old array, add d to the end of old data*/

{

++size;

double * newarray = new double[size];

for(int i=0;i<size-1;i++)

{

newarray[i] = data[i];

}

newarray[size-1] = d;

delete[] data;

data = newarray;

}


private:

double *data;

int size;

};


int main()

{

cout << "Hello world!" << endl;

DynamicDouble dd(2);

dd.PushBack(5);

dd.PushBack(3);

dd.print();


return 0;

}