No viable overloaded '='

I'm writing a small linear algebra library to use with some OpenGL stuff. In my Matrix class I have the following two operators defined:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Matrix4 Matrix4::operator*(Matrix4& m) {
    Matrix4 r;
    int index = 0;
    
    for(int col = 0; col < 4; col++) {
        for(int row = 0; row < 4; row++) {
            float sum = 0.0f;
            for(int i = 0; i < 4; i++) {
                sum += m.raw()[i + col * 4]*mat[row + i * 4];
            }
            r.raw()[index] = sum;
            index++;
        }
    }
    
    return r;
}

Matrix4& Matrix4::operator=(Matrix4& m) {
    for(int i = 0; i < 16; i++) {
        mat[i] = m.raw()[i];
    }
    return *this;
}


And I'm trying to translate an existing matrix every frame, by doing

1
2
Matrix4 t = Matrix4::translation(elapsed * speed + lastPos, 0.0, 0.0);
matrix = matrix * t; //ERROR HERE 


But I'm getting a compiler error saying 'No viable overloaded '=''. Why would it say that when I clearly have overloaded the operator, and the types are correct?
Last edited on
A temporary object can't bind to a non-const reference. You have to mark the parameter m of operator= as const.
 
Matrix4& Matrix4::operator=(const Matrix4& m) {


You should also mark operator* as const (both the parameter and the function).
 
Matrix4 Matrix4::operator*(const Matrix4& m) const {
This is not needed for your example code to compile but in some cases it will be needed (e.g. if you multiply three matrices at once).
Look at the canonical copy assignment operators in http://en.cppreference.com/w/cpp/language/operators

There are
1
2
Matrix4& Matrix4::operator=( Matrix4 m )
Matrix4& Matrix4::operator=( const Matrix4 & m )

but you have only
Matrix4& Matrix4::operator=( Matrix4 & m )

The thing is that the matrix * t creates an unnamed, temporary Matrix4 object and taking the address of that is not ok.

Forcing a copy/move is ok and taking address to const is ok.
OK, thanks :)
Topic archived. No new replies allowed.