Given the following class that does dynamic allocation, add the destructor, a copy constructor, and an overloaded assignment operator to the class. Write a test program which verifies that your assignment operator and copy constructor correctly duplicate the dynamic memory contained in an object of the class.
This is what I have:
.h file
Code:
#pragma once
class Matrix
{
private:
double *matrix;
int rows, cols;
public:
Matrix(int r = 10, int c = 10);
~Matrix(); //destructor
Matrix(const Matrix& MatrixTwo); //Copy constructor
const Matrix& operator=(const Matrix&); //overloading operator
void getDataFromUser( );
void displayToConsole( ) const;
void setElement(int r, int c, double v);
double getElement(int r, int c);
};
Code:
#include <iostream>
#include "Matrix.h"
using namespace std;
Matrix::Matrix(int r, int c)
{
rows = r;
cols = c;
matrix = new double[r * c];
}
void Matrix::getDataFromUser( )
{
for(int i = 0; i < rows; i++)
{
cout << "Input " << cols << " values for row " << i << endl;
for(int j = 0; j < cols; j++)
{
cin >> matrix[i * cols + j];
}
cout << endl;
}
}
void Matrix::displayToConsole( ) const
{
cout << endl;
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << matrix[i * cols + j] << " ";
}
cout << endl;
}
cout << endl;
}
void Matrix::setElement(int r, int c, double v)
{
matrix[r * cols + c] = v;
}
double Matrix::getElement(int r, int c)
{
return matrix[r * cols + c];
}
Matrix::~Matrix() //destructor
{
delete [] matrix;
}
Matrix::Matrix(const Matrix& MatrixTwo) //copy
{
rows = MatrixTwo.rows;
cols = MatrixTwo.cols;
matrix = new double[rows];
for(int i=0; i < cols; i++)
matrix[i] = MatrixTwo.matrix[i];
}
const Matrix& Matrix::operator=(const Matrix& MatrixTwo)//overloader
{
if(this != &MatrixTwo) //avoid self-assignment
{
}
//return the object that was assigned to
return *this;
}
Code:
#include <iostream>
#include "Matrix.h"
using namespace std;
void test(Matrix temp);
int main()
{
Matrix listOne;
int r;
int c;
cout << "Enter integers:" << endl;
for(r=0; r<10; r++)
{
cin >> c;
}
cout << "listOne:" << listOne;
cout << endl;
Matrix listTwo(listOne);
cout << "listTwo: " << listTwo;
cout << endl;
test(listOne) << listOne;
cout << endl;
return 0;
}
void test(Matrix temp)
{
cout << "Test" << endl << temp;
cout << endl;
}
