N
N
newmersedez2020-12-28 02:55:59
C++ / C#
newmersedez, 2020-12-28 02:55:59

What should the matrix class method return?

I am writing a square matrix class, here, in fact, the class itself:

matrix.h
#ifndef MATRIX_H
#define MATRIX_H

#include <string.h>

class Matrix
{
private:
    std::string name;
    double      **matrix;
    int         size;
public:
    // Default constructor
    Matrix() : name("NaN"), matrix(nullptr), size(0)
    { }

    // Constructor with values
    Matrix(std::string nm, int sz) : name(nm), size(sz)
    {
        try 
        {
            matrix = new double *[size];
            for(int i = 0; i < size; i++)
                matrix[i] = new double[size];
        }
        catch(std::bad_alloc& ex)
        {
            std::cerr << ex.what() << std::endl;
        }
    }

    // Arithmetic shit
    bool    operator== (const Matrix &operand);
    bool    operator!= (const Matrix &operand);
    Matrix  operator+(const Matrix &operand);
};

#endif

matrix.cpp
#include <iostream>
#include "matrix.h"

/*  return 1 if ==
    return 0 if !=*/
bool Matrix::operator== (const Matrix &operand)
{
    if(operand.size != this->size)
        return 0;
    for(int i = 0; i < this->size; i++)
    {
        if(this->matrix[i][i] != operand.matrix[i][i])
            return 0;
    }
    return 1;
}

/*  return 1 if !=
    return 0 if ==*/
bool Matrix::operator!= (const Matrix &operand)
{
    if(operand.size != this->size)
        return 1;
    for(int i = 0; i < this->size; i++)
    {
        if(this->matrix[i][i] != operand.matrix[i][i])
            return 1;
    }
    return 0;
}

Matrix Matrix::operator+ (const Matrix &operand)
{
    const Matrix result;
    //pass
}


My question is about the addition operator. This method returns an object of the class. We can only add matrices of the same order. If, for example, matrices of a different order, or if I catch a bad memory allocation through an exception handler, then what should this method return if the operation cannot be performed?
nullptrwe cannot return.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2020-12-28
@newmersedez

1. There is no destructor in your code that would free memory => you have a potential memory leak.
2. In the case of the addition operator, if the matrices have different sizes, throw an exception through std::runtime_error
3. You do not have a copy constructor and when copying an object, a pointer to the allocated memory will be copied.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question