Seb
Seb

Reputation: 2016

Overloading operator and chaining

I have a class, with object 'matrix' that stores a dynamic 2D array. I'm trying to overload the '=' operator so that 1 matrix can copied onto another.

The following works:

Square_Matrix a,b,c;
a = b;

However, this doesn't work:

a = b = c;

^ It gives me the following errors 1) no match for operator= (operand types are 'Square_Matrix' and 'void') ..... 2) no known conversion for argument 1 from 'void' to 'const Square_Matrix'

How can I fix this?

//header file
void operator=(const Square_Matrix& Par2);

//.cpp file
void Square_Matrix::operator=(const Square_Matrix& Par2){
    if (size != Par2.size){
        cout << "Matrices are of different size" << endl;
    } else {
        for (int i = 0; i < N; i++){
            for (int j = 0; j < N; j++){
                 matrix[i][j] = Par2.matrix[i][j];
            }
        }
    }
}

Upvotes: 0

Views: 92

Answers (2)

rajenpandit
rajenpandit

Reputation: 1361

As per you code the function is returning void so in a=b=c, b=c is returning void that becomes a=void and there is no such function defined which take void as argument. because of this you are getting that error. to avoid this you should return a reference of Squar_Matrix object.

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119134

You need to return a reference to the assigned object.

Square_Matrix& Square_Matrix::operator=(const Square_Matrix& Par2){
    // do stuff
    return *this;
}

Upvotes: 4

Related Questions