overloading the addition and multiplication operators for the matrix class - c++

I implement the overloading of the addition and multiplication operators for the matrix class. I can't understand where the error is, or rather, I guess that there is an error in the declaration of operators, but I have no idea how to fix it specifically.
Can someone suggest a good book on object oriented programming. I feel that I am clearly lacking information
#include <iostream>
using namespace std;
template <typename T>
class MATRIX
{
private:
T** M;
int m;
int n;
public:
MATRIX()
{
n = m = 0;
M = nullptr;
}
MATRIX(int _m, int _n)
{
m = _m;
n = _n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*)new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = 0;
}
MATRIX(const MATRIX& _M)
{
m = _M.m;
n = _M.n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*) new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = _M.M[i][j];
}
T GetMij(int i, int j)
{
if ((m > 0) && (n > 0))
return M[i][j];
else
return 0;
}
void SetMij(int i, int j, T value)
{
if ((i < 0) || (i >= m))
return;
if ((j < 0) || (j >= n))
return;
M[i][j] = value;
}
void Print(const char* ObjName)
{
cout << "Object: " << ObjName << endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cout << M[i][j] << "\t";
cout << endl;
}
cout << "---------------------" << endl << endl;
}
MATRIX operator=(const MATRIX& _M)
{
if (n > 0)
{
for (int i = 0; i < m; i++)
delete[] M[i];
}
if (m > 0)
{
delete[] M;
}
m = _M.m;
n = _M.n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*) new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = _M.M[i][j];
return *this;
}
MATRIX operator+(const MATRIX& _M) {
MATRIX M6(_M.n, _M.m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
M6.M[i][j] = _M.M[i][j]+this-> M[i][j];
}
return M6;
}
MATRIX operator*(const MATRIX& _M) {
MATRIX M5(_M.n, _M.m);
for (int i = 0; i < _M.n; i++)
{
for (int j = 0; j < _M.m; j++)
{
for (int k = 0; k < m; k++)
{
M5.M[i][j] += M[i][k]*_M.M[k][j];
}
}
}
return M5;
}
bool operator ==(const MATRIX& _M) {
return this->n == _M.n && this->m == _M.m;
}
bool operator !=(const MATRIX& _M) {
return !(this->n == _M.n && this->m == _M.m);
}
~MATRIX()
{
if (n > 0)
{
for (int i = 0; i < m; i++)
delete[] M[i];
}
if (m > 0)
delete[] M;
}
};
void main()
{
MATRIX<int> M(2, 3);
M.Print("M");
int i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
M.SetMij(i, j, i + j);
M.Print("M");
MATRIX<int> M2 = M;
M2.Print("M2");
MATRIX<int> M3;
M3 = M;
M3.Print("M3");
MATRIX<int> M4;
M4 = M3 = M2 = M;
M4.Print("M4");
////////////////////////
bool result = M == M3;// ==
if (result == 1) {
cout << "true";
}
else if (result == 0) {
cout << "false";
}
cout << endl << "---------------------" << endl << endl;
//////////////////////////
bool result1 = M != M3;// !=
if (result1 == 1) {
cout << "true";
}
else if (result1 == 0) {
cout << "false";
}
cout << endl << "---------------------" << endl << endl;
MATRIX<int> M1;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
M1.SetMij(i, j, i + j);
M1.Print("M1");
M.Print("M");
MATRIX<int> M6 = M + M1;
M6.Print("M");
MATRIX<int> M5 = M * M1;
M5.Print("M");
}```
thanks in advance
[enter image description here][1]
[1]: https://i.stack.imgur.com/TjEOp.png

I belive that std::vector is better
MATRIX() {}
MATRIX(int r, int c) : M(r * c, T()) , rows(r), cols(c) { }
// Does not need copy constructor
// Does not need operator =
// Does not need destructor
also you can proxy row and cols to overload []
MATRIX<int> x(3,3);
x[2][2] = 10;
also a generating function is welcome
template<typename GenT> void generate( GenT gen ) {...}
https://godbolt.org/z/dK6Tqc

Related

Matrix class content using shared_ptr?

class Matrix
{
private:
int rows;
int cols;
int** Mat;
public:
Matrix(){}
Matrix(const int& rows, const int& cols):rows(rows),cols(cols)
{
Mat = new int* [cols];
for (int i = 0; i < rows; i++)
{
Mat[i] = new int[cols]();
}
}
Matrix operator +(const Matrix& other)const
{
Matrix temp(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
temp.Mat[i][j] += other.Mat[i][j] + Mat[i][j];
return temp;
}
My question is regarding how I'd use shared_ptr and make_shared to replace int** Mat? and, after that, how do I use it in the constructor and operator+? It's a custom matrix class that should add matrices
#include <iostream>
#include <memory>
#include <cassert>
class Matrix {
private:
int rows;
int cols;
std::shared_ptr<std::shared_ptr<int>> Mat;
public:
Matrix() = default;
Matrix(const int& rows, const int& cols) : rows(rows), cols(cols)
{
Mat.reset(new std::shared_ptr<int>[rows], [](std::shared_ptr<int>* p) { delete[] p; });
for (int i = 0; i < rows; ++i)
{
Mat.get()[i].reset(new int[cols], [](int* p) { delete[] p; });
}
for (int i = 0; i < (*this).rows; ++i)
for (int j = 0; j < (*this).cols; ++j)
(*this)[i][j] = 0;
}
int* operator[](const int& index) const
{
return Mat.get()[index].get();
}
Matrix(const Matrix& other) : cols(other.cols), rows(other.rows)
{
Mat.reset(new std::shared_ptr<int>[rows], [](std::shared_ptr<int>* p) { delete[] p; });
for (int i = 0; i < rows; ++i)
{
Mat.get()[i].reset(new int[other.cols], [](int* p) { delete[] p; });
}
for (int i = 0; i < other.rows; i++)
for (int j = 0; j < other.cols; j++)
(*this)[i][j] = other[i][j];
}
Matrix& operator=(const Matrix& other)
{
if (Mat != other.Mat && cols == other.cols && rows == other.rows)
{
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
(*this)[i][j] = other[i][j];
return *this;
}
else
return *this;
}
Matrix operator+(const Matrix& other) const
{
Matrix temp(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
temp[i][j] += other[i][j] + (*this)[i][j];
return temp;
}
friend std::ostream& operator<<(std::ostream& os, Matrix& m)
{
for (int i = 0; i < m.rows; ++i)
{
for (int j = 0; j < m.cols; ++j)
{
os << m[i][j] << " ";
}
os << std::endl;
}
return os;
}
};
int main()
{
Matrix a(2, 2);
a[0][0] = 1;
a[0][1] = 1;
std::cout << a << std::endl;
Matrix b(2, 2);
b[1][1] = 1;
b[1][0] = 1;
std::cout << b << std::endl;
b[1][0] = 9;
Matrix c(a);
c[0][0] = 6;
std::cout << c << std::endl;
Matrix d = b;
std::cout << d << std::endl;
Matrix e = a + b;
std::cout << e << std::endl;
}
I have solved it myself in the end :D

Segmentation Fault Error Dealing with Matrices (Arrays)

I'm trying to reference a 2D array object I've constructed, but for whatever reason I'm getting a segmentation fault and I'm having trouble figuring out the cause. So far I've deduced that the error lies in my operator<< function, but I can't figure out what to change.
main.cpp:
int main() {
My_matrix m1(3, 2);
cout << "Before" << endl;
m1(0,0) = 1; //causes segfault
cout << "After" << endl;
m1(0,1) = 2; //causes segfault
m1(1,0) = 3; //causes segfault
m1(1,1) = 4; //causes segfault
m1(2,0) = 5; //causes segfault
m1(2,1) = 6; //causes segfault
cout << "Checkpoint 1" << endl;
My_matrix m2(); //works
cout << "Checkpoint 2" << endl;
cout << m1.number_of_rows() << endl; //works
cout << "Checkpoint 3" << endl;
cout << m1; //Segfault
cout << "Checkpoint 4" << endl;
cout << m1; //Segfault
cout << "Checkpoint 5" << endl;
cout << m2; //Segfault
cout << "Checkpoint 6" << endl;
}
My_matrix.cpp:
#include "My_matrix.h"
#include <stdexcept>
My_matrix::My_matrix()
{
n = 0;
m = 0;
ptr = nullptr;
}
My_matrix::My_matrix(int n1, int m1)
{
n = n1;
m = m1;
ptr = new int*[n];
for(int i = 0; i < n; i++) {
ptr[i] = new int[m];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ptr[i][j] = 0;
}
}
}
My_matrix::My_matrix(const My_matrix& mat)
{
this->n = mat.n;
this->m = mat.m;
ptr = new int*[n];
for(int i = 0; i < n; i++) {
ptr[i] = new int[m];
}
//----- copy elements over to new matrix -----//
for (int i = 0; i < mat.n; i++) {
for (int j = 0; j < mat.m; j++) {
this->ptr[n][m] = mat.ptr[n][m];
}
}
}
My_matrix::~My_matrix()
{
clear();
}
My_matrix& My_matrix::operator=(const My_matrix& mat)
{
clear();
this->n = mat.n;
this->m = mat.m;
ptr = new int*[n];
for(int i = 0; i < n; i++) {
ptr[i] = new int[m];
}
//----- copy elements over -----//
for (int i = 0; i < mat.n; i++) {
for (int j = 0; j < mat.m; j++) {
this->ptr[n][m] = mat.ptr[n][m];
}
}
}
int My_matrix::number_of_rows() const
{
return n;
}
int My_matrix::number_of_columns() const
{
return m;
}
int* My_matrix::operator()(int i) const
{
return ptr[i];
}
int& My_matrix::operator()(int i, int j) const
{
return ptr[n][m];
}
int& My_matrix::operator()(int i, int j)
{
return ptr[n][m];
}
int& My_matrix::elem(int i, int j) const
{
if (i < 0 || i >= n) throw out_of_range("Out of range");
if (j < 0 || j >= m) throw out_of_range("Out of range");
return ptr[n][m];
}
int& My_matrix::elem(int i, int j)
{
if (i < 0 || i >= n) throw out_of_range("Out of range");
if (j < 0 || j >= m) throw out_of_range("Out of range");
return ptr[n][m];
}
void My_matrix::clear()
{
for (int i = 0; i < n; i++) {
delete[] ptr[i];
}
delete[] ptr;
n = 0;
m = 0;
}
ostream& operator<<(ostream& out, const My_matrix& mat)
{
for (int i = 0; i < mat.number_of_rows(); i++) {
for (int j = 0; j < mat.number_of_columns(); j++) {
out << mat(i, j) << " "; //This line is the culprit ****
}
out << endl;
}
return out;
}
As hinted at by #WhozCraig and #O'Neil in the comments, I had a few typos in my code which referred to indices that were not in bounds of the matrix I had created. Rather than using the iterators/function arguments, I used n and m, which represent the size of the matrix, which is obviously one larger than the largest index. Examples include:
int& My_matrix::elem(int i, int j) const
{
if (i < 0 || i >= n) throw out_of_range("Out of range");
if (j < 0 || j >= m) throw out_of_range("Out of range");
return ptr[n][m]; //<--- should be return ptr[i][j];
}
as well as
My_matrix::My_matrix(const My_matrix& mat)
{
this->n = mat.n;
this->m = mat.m;
ptr = new int*[n];
for(int i = 0; i < n; i++) {
ptr[i] = new int[m];
}
//----- copy elements over to new matrix -----//
for (int i = 0; i < mat.n; i++) {
for (int j = 0; j < mat.m; j++) {
this->ptr[n][m] = mat.ptr[n][m]; //<--- should be this->ptr[i][j] = mat.ptr[i][j];
}
}
}
By correcting these discrepancies my issue was resolved.

Access violation reading location - creating matrix class

This is supposed to be my HW in OOP course. SO i asked to create matrix class. Code works fine - all methods and new operands works fine BUT when my D`tor is empty and when i write there code to free memory i get this error. Thanks for help
int main()
{
MyMatrix m1(3, 3);
MyMatrix m2(3, 3);
MyMatrix res(3, 3);
m1.Set();
m2.Set();
cout << m1;
cout << m2;
res = m1 + m2;
cout << res;
}
CPP
MyMatrix::MyMatrix(int row, int col) // C`tor with specific data
{
n = row;
m = col;
matrix = new int* [n]; // Memory allocation for rows
for (int i = 0; i < n; i++)
{
matrix[i] = new int[m]; // Memory Allocation for columns
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = 0;
}
}
}
MyMatrix::~MyMatrix() // Default d`tor
{
for (int i = 0; i < n; i++)
{
delete[] matrix[i];
}
delete[] matrix;
}
void MyMatrix::Set()
{
cout << "Enter new row" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> matrix[i][j];
}
if (i != (n - 1))
{
cout << "Enter new row" << endl;
}
}
}
ostream& operator<<(ostream& out, const MyMatrix& matrix)
{
for (int i = 0; i < matrix.n; i++)
{
//run in loop on every column.
for (int j = 0; j < matrix.m; j++)
//print value with a space.
out << matrix.matrix[i][j] << "t";
//at the end of every row jump line.
out << endl;
}
out << endl;
return out;
}
MyMatrix& MyMatrix::operator= (const MyMatrix& mat1)
{
n = mat1.n;
m = mat1.m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = mat1.matrix[i][j];
}
}
return *this;
}
const MyMatrix MyMatrix::operator+(const MyMatrix& mat1) const
{
MyMatrix temp(n, m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
temp.matrix[i][j] = matrix[i][j] + mat1.matrix[i][j];
}
}
return temp;
}
H file
class MyMatrix
{
private:
int **matrix;
int n, m;
public:
MyMatrix(int a, int b);
~MyMatrix();
void Set();
const MyMatrix operator+ (const MyMatrix& mat1) const;
MyMatrix& operator= (const MyMatrix& mat1);
friend ostream& operator<<(ostream& out, const MyMatrix& matrix);
};

C++ OOP - Arrays (matrices) multiplication, deleting object [duplicate]

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 7 years ago.
I am writing simple C++ application to multiply two matrices. Yes, I am aware this version doesn't check e.g. whether number of rows is greater than zero.
I can create two objects using a default constructor and I can create third object (a result of multiplication of two previous objects of the same class). I can't however correctly delete this third object. When I try, an "Access violation reading location" exception is throw. Can you tell me what am I missing? Is there something I forget to initialize? This exception is only thrown when using myThirdFunction.
Any other advice on making this code better is welcome :)
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
class MyArray
{
int Variable1 = 0;
int Variable2 = 0;
float ** myArray;
public:
MyArray() : Variable1(0), Variable2(0){ myFunction(); }
MyArray (int variable1, int variable2) : Variable1(variable1):
Variable2(variable2){ myFunction(); }
MyArray(const MyArray &myArrayA, const MyArray &myArrayB) :
Variable1(myArrayA.Variable1), Variable2(myArrayB.Variable2)
{ myThirdFunction(myArrayA, myArrayB); }
MyArray(const MyArray &myArray)
{ Variable1=myArray.Variable1; Variable2 = myArray.Variable2;
this->myArray =myArray.myArray; }
void myFunction() {
cin >> Variable1;
cin >> Variable2;
myArray = new float*[Variable1];
myOtherFunction();
}
void myOtherFunction() {
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = rand() % (10 - 0) + 0;
}
}
void myThirdFunction(MyArray myArrayA, MyArray myArrayB)
{
Variable1 = myArrayA.Variable1;
Variable2 = myArrayB.Variable2;
myArray = new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
{
float tempVariable = 0;
for (int q = 0; q < myArrayA.Variable2; ++q)
{
tempVariable += myArrayA.myArray[i][q] * myArrayB.myArray[q][j];
}
myArray[i][j] = tempVariable;
}
}
}
void displayMyArray() {
for (int i = 0; i < Variable1; ++i)
{
for (int j = 0; j < Variable2; ++j)
cout << myArray[i][j] << '\t';
cout << endl;
}
}
~MyArray() {
for (int i = 0; i < Variable1; ++i)
{
delete[] myArray[i];
}
delete[]myArray;
}
};
int main(){
srand(time(0));
MyArray myArrayA;
myArrayA.displayMyArray();
cout << endl;
MyArray myArrayB;
myArrayB.displayMyArray();
cout << endl;
MyArray myArrayC(myArrayA, myArrayB);
myArrayC.displayMyArray();
getchar();
getchar();
return 0;
}
Thanks :)
The member myArray is a pointer, and in your copy constructor you just copy the pointer without creating a new array. Because myThirdFunction takes both arguments by value, it creates two copies of the original objects. And because the copy constructor doesn't create a new value, when those two copies go out of scope at the end of the function, the original pointers now point to deallocated memory. Whenever the original two objects are destroyed, the destructor tries to delete memory that was already deleted.
From the beginning, you have this constructor:
MyArray(const MyArray &myArrayA, const MyArray &myArrayB)
{
myThirdFunction(myArrayA, myArrayB); //This call creates two new objects
}
The signature of myThirdFunction being void myThirdFunction(MyArray myArrayA, MyArray myArrayB), you pass by value and create two new copies. That calls the copy constructors for the two parameters:
MyArray(const MyArray &myArray)
{
this->myArray =myArray.myArray; //shallow copy, very bad
}
The new objects now point to the same memory as the originals. So, when they are destroyed at the end of myThirdFunction, the original pointers become garbage. In a broad view, this happens. float* p = new float; delete p; delete p; The solution is to make the copy constructor actually copy the elements, not the pointers:
MyArray(const MyArray &p_copy) //The name confused me so I changed it
{
Variable1 = p_copy.Variable1;
Variable2 = p_copy.Variable2;
myArray new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = p_copy.myArray[i][j];
}
}
In addition, you probably want to pass to myThirdFunction by constant reference.
void myThirdFunction(const MyArray& myArrayA, const MyArray& myArrayB)
I don't see a need to create two temporary objects here.
At the first time this code will works.
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
class MyArray
{
int Variable1;
int Variable2;
float ** myArray;
public:
MyArray() : myArray(NULL), Variable1(0), Variable2(0) // initialize pointers with NULL is important
{
myFunction();
}
MyArray (int variable1, int variable2) : myArray(NULL), Variable1(variable1),
Variable2(variable2)
{
myFunction();
}
MyArray(const MyArray &myArrayA, const MyArray &myArrayB) : myArray(NULL),
Variable1(myArrayA.Variable1), Variable2(myArrayB.Variable2)
{
myThirdFunction(myArrayA, myArrayB);
}
MyArray(const MyArray &myArray)
{
Variable1=myArray.Variable1; Variable2 = myArray.Variable2;
this->myArray =myArray.myArray;
}
void myFunction()
{
cin >> Variable1;
cin >> Variable2;
myArray = new float*[Variable1];
myOtherFunction();
}
void myOtherFunction()
{
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = rand() % (10 - 0) + 0;
}
}
void myThirdFunction(MyArray myArrayA, MyArray myArrayB)
{
// cols of first must be same as rows of second
if (myArrayA.Variable2 != myArrayB.Variable1)
return;
// memory must be cleaned before new array creation
clearArray();
Variable1 = myArrayA.Variable1;
Variable2 = myArrayB.Variable2;
myArray = new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
{
float tempVariable = 0;
for (int q = 0; q < myArrayA.Variable2; ++q)
{
tempVariable += myArrayA.myArray[i][q] * myArrayB.myArray[q][j];
}
myArray[i][j] = tempVariable;
}
}
}
void displayMyArray()
{
for (int i = 0; i < Variable1; ++i)
{
for (int j = 0; j < Variable2; ++j)
cout << myArray[i][j] << '\t';
cout << endl;
}
}
~MyArray()
{
clearArray();
}
// clear memory and deinitialize pointers
void clearArray()
{
if (myArray == NULL)
return;
for (int i = 0; i < Variable1; ++i)
{
delete[] myArray[i];
myArray[i] = NULL;
}
delete[]myArray;
myArray = NULL;
}
};
int main(){
srand(time(0));
MyArray myArrayA;
myArrayA.displayMyArray();
cout << endl;
MyArray myArrayB;
myArrayB.displayMyArray();
cout << endl;
MyArray myArrayC(myArrayA, myArrayB);
myArrayC.displayMyArray();
getchar();
getchar();
return 0;
}
but I strongly recomend you to create proper copy constructor and assignment operator means (operator=) to proper object creation and destruction.
Here I post my own matrix realization to refer you in what way you can approve your code.
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
using namespace std::
class Matrix
{
public:
Matrix();
Matrix(int rowcount,int colcount);
Matrix(int rowcount,int colcount,float* matrix);
Matrix(const Matrix& rhs);
~Matrix();
/////////////////////////////////////////////////////////////
Matrix& operator = (const Matrix& rhs);
Matrix operator + (const Matrix& rhs);
Matrix operator - (const Matrix& rhs);
Matrix operator * (float scale);
Matrix operator * (const Matrix& rhs);
void operator += (const Matrix& rhs);
void operator -= (const Matrix& rhs);
void operator *= (float scale);
void operator *= (const Matrix& rhs);
float operator [] (int offset) const;
float& operator [] (int offset);
friend ostream& operator << (ostream& _str,const Matrix& rhs);
/////////////////////////////////////////////////////////////
void setCols(int cols);
void setRows(int rows);
void setMatrix(float* matrix);
int getCols() const
{
return itsCols;
}
int getRows() const
{
return itsRows;
}
const float* getMatrix() const
{
Invariants();
return itsMatrix;
}
void Invariants() const
{
if ((!(itsCols && itsRows && itsMatrix)) && (itsRows < 0) && (itsCols < 0))
{
cout << "Not allowed action!\n";
getch();
exit(0);
}
}
/////////////////////////////////////////////////////////////
private:
float* itsMatrix;
int itsRows;
int itsCols;
};
Matrix::Matrix()
{
itsRows = 0;
itsCols = 0;
itsMatrix = NULL;
}
Matrix::Matrix(int rowcount,int colcount)
{
itsRows = rowcount;
itsCols = colcount;
itsMatrix = new float[itsRows * itsCols];
Invariants();
}
Matrix::Matrix(int rowcount,int colcount,float* matrix)
{
itsRows = rowcount;
itsCols = colcount;
itsMatrix = new float[itsCols * itsRows];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = matrix[counter];
counter++;
}
}
Invariants();
}
Matrix::Matrix(const Matrix& rhs)
{
itsCols = rhs.getCols();
itsRows = rhs.getRows();
itsMatrix = new float[itsRows * itsCols];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = rhs[counter];
counter++;
}
}
}
Matrix::~Matrix()
{
itsCols = 0;
itsRows = 0;
delete [] itsMatrix;
itsMatrix = NULL;
}
Matrix& Matrix::operator = (const Matrix& rhs)
{
if (&rhs == this)
return *this;
else
{
itsRows = rhs.getRows();
itsCols = rhs.getCols();
delete [] itsMatrix;
itsMatrix = NULL;
itsMatrix = new float[itsRows * itsCols];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = rhs[counter];
counter++;
}
}
return *this;
}
}
float& Matrix::operator [] (int offset)
{
Invariants();
if ((offset > -1) && (offset < itsCols * itsRows))
return itsMatrix[offset];
else
{
cout << "You cann't reach this element!\n";
getch();
exit(0);
}
return itsMatrix[offset];
}
float Matrix::operator [] (int offset) const
{
Invariants();
if ((offset > -1) && (offset < itsCols * itsRows))
return itsMatrix[offset];
else
{
cout << "You cann't reach this element!\n";
getch();
exit(0);
}
return 0;
}
Matrix Matrix::operator + (const Matrix& rhs)
{
Invariants();
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform addiction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] + rhs[counter];
counter++;
}
}
return temp;
}
Matrix Matrix::operator - (const Matrix& rhs)
{
Invariants();
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform substraction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] - rhs[counter];
counter++;
}
}
return temp;
}
Matrix Matrix::operator * (float scale)
{
Invariants();
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] * scale;
counter++;
}
}
return temp;
}
Matrix Matrix::operator * (const Matrix& rhs)
{
Invariants();
if (!(itsCols == rhs.getRows()))
{
cout << "Cann't perform multiplication of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,rhs.getCols());
int counter = 0;
float sum = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
for (int k = 0; k < itsCols; k++)
{
sum += itsMatrix[i * itsCols + k] *
rhs[k * rhs.getCols() + j];
}
temp[counter] = sum;
sum = 0;
counter++;
}
}
return temp;
}
void Matrix::operator += (const Matrix& rhs)
{
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform addiction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] + rhs[counter];
counter++;
}
}
*this = temp;
}
void Matrix::operator -= (const Matrix& rhs)
{
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform substraction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] - rhs[counter];
counter++;
}
}
*this = temp;
}
void Matrix::operator *= (float scale)
{
Invariants();
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] * scale;
counter++;
}
}
*this = temp;
}
void Matrix::operator *= (const Matrix& rhs)
{
Invariants();
if (!(itsCols == rhs.getRows()))
{
cout << "Cann't perform multiplication of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,rhs.getCols());
int counter = 0;
float sum = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
for (int k = 0; k < itsCols; k++)
{
sum += itsMatrix[i * itsCols + k] *
rhs[k * rhs.getCols() + j];
}
temp[counter] = sum;
sum = 0;
counter++;
}
}
*this = temp;
}
ostream& operator << (ostream& _str,const Matrix& rhs)
{
rhs.Invariants();
int counter = 0;
for (int i = 0; i < rhs.getRows(); i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
_str << rhs[counter] << "\t";
counter++;
}
_str << endl;
}
return _str;
}
float arr1[] =
{
2, 2, 2,
-1, -3, -5,
16, 8, 24,
8, 0, 16
};
float arr2[] =
{
15,
2,
-4
};
int main()
{
clrscr();
Matrix m1(4,3,arr1);
Matrix m2(3,1,arr2);
cout << "Matrix 1:\n";
cout << m1 << endl;
cout << "Matrix 2:\n";
cout << m2 << endl;
cout << "Matrix 1 * Matrix 2\n";
cout << m1 * m2 << endl;
getch();
cout << "Matrix 1 + Matrix 1\n";
cout << m1 + m1 << endl;
getch();
cout << "Matrix 1 - Matrix 1\n";
cout << m1 - m1 << endl;
getch();
cout << "Matrix 1 * 4\n";
cout << m1 * 4 << endl;
getch();
return 0;
}

Operator overloading with dynamic allocated matrix

I'm writting some code for teaching myself C++.
Does the following code:
#include <iostream>
using namespace std;
class Matrix
{
int m, n;
public:
float** value;
Matrix(int m, int n)
{
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
this->m = m; this->n = n;
}
~Matrix()
{
for (int i = 0; i < m; ++i)
delete[] value[i];
delete[] value;
}
Matrix(const Matrix& A)
{
m = A.getLength();
n = A.getWidth();
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
value[i][j] = A.value[i][j];
}
int getLength(void) const
{
return m;
}
int getWidth(void) const
{
return n;
}
void print() const
{
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
cout << value[i][j] << "\t";
cout << endl;
}
}
Matrix operator + (const Matrix& B)
{
if (m != B.getLength() || n != B.getWidth())
return Matrix(0, 0);
Matrix C = Matrix(m, n);
cout << value << endl;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
C.value[i][j] = value[i][j] + B.value[i][j];
return C;
}
void operator = (const Matrix& A)
{
m = A.getLength();
n = A.getWidth();
value = new float*[m];
for (int i = 0; i < m; ++i)
value[i] = new float[n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
value[i][j] = A.value[i][j];
}
};
int main()
{
Matrix A = Matrix(3, 3);
A.value[0][0] = 1; A.value[0][1] = 2; A.value[0][2] = 3;
A.value[1][0] = 4; A.value[1][1] = 5; A.value[1][2] = 6;
A.value[2][0] = 7; A.value[2][1] = 8; A.value[2][2] = 9;
Matrix B = Matrix (3, 3);
B.value[0][0] = 1; B.value[0][1] = 2; B.value[0][2] = 3;
B.value[1][0] = 4; B.value[1][1] = 5; B.value[1][2] = 6;
B.value[2][0] = 7; B.value[2][1] = 8; B.value[2][2] = 9;
Matrix C = A + B;
cout << C.value << endl;
C.print();
return 0;
}
Generate a memory leak at the part "Matrix C = A + B"? I don't know if the returned matrix is destroyed after the association is done. If yes, is there a way to fix it?
In statement
Matrix C = A + B;
there is no leak.
Though in your code the copy assignment operator is not used nevertheless your copy assignment operator does not free the memory previously allocated to the matrix of an object.
The copy assignment operator differs from the copy constructor in that that the object is already created and has an allocated matrix. Also you have to check whether there is the self assignment.
Also it should be declared as
Matrix & operator = (const Matrix& A)
As for operator + then it should be declared as
Matrix operator + (const Matrix& B) const;
or as
const Matrix operator + (const Matrix& B) const;