Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the operator overloading fail when i try to sum a number plus a matrix? (but it works the opposite way)

Here's the code of my matrix class:

class Matrix3{
public:
    double matrix [3][3];

The needed constructors and the + operator:

Matrix3::Matrix3(double num){
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            matrix[i][j] = num;
}

Matrix3::Matrix3(const Matrix3 &other){
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            this->matrix[i][j] = other.matrix[i][j];
}

Matrix3 Matrix3::operator+(const Matrix3& other) const{
    Matrix3 temp(*this);
    for(int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            temp.matrix[i][j] += other.matrix[i][j];

    return temp;
}

main:

    Matrix3 a1;     // All Elements are 0 (default)
    Matrix3 a2(a1); // a2 initialize with a1
    Matrix3 a4(4);  // All Elements are 4

    a1 = a1 + 3;   //it works
    a2 = 3 + a2;   //it doesn't, it says: "invalid operands to binary expression"
    a4 = a1 + a2;  //it works too

So i don't understand why does the first one work. in both case it should create a matrix in which all elemets are 3 because there is a constructor for that and add it to the onether matrix. Any idea?

like image 783
Rena821 Avatar asked Mar 03 '23 15:03

Rena821


1 Answers

It's because you declared operator+ as a member function. This is a bad idea because of exactly the problem you have found. When operator+ is a member function the C++ compiler will do automatic conversions on the right hand side but not on the left hand side.

Fix this by making your operator+ a global function with two arguments

Matrix3 operator+(const Matrix3& lhs, const Matrix3& rhs) {
    ...
}

Now the conversion from double to Matrix will be done on either argument.

like image 97
john Avatar answered Apr 06 '23 00:04

john