Reputation: 330
I got a class Matrix
and a class Row
. Matrix
has as member variable a pointer to a pointer of an object from class Row
. I overloaded the operator [] for Matrix
and Row
. But somehow the overloaded operator from Row
is never getting called and I can't figure out why not.
Example Code: matrix.h
class Row
{
int* value;
int size;
public:
int& operator[](int i)
{
assert(i >= 0 && i < size);
return value[i];
}
};
class Matrix
{
private:
Row **mat; // Pointer to "Row"-Vector
int nrows, ncols; // Row- and Columnnumber
public:
Row& Matrix::operator[](int i){
assert(i >= 0 && i < nrows);
return *mat[i];
}
Row** getMat() {
return mat;
}
// Constructor
Matrix(int rows, int cols, int value);
};
matrix.cpp
#include "matrix.h"
Matrix::Matrix(int rows, int cols, int value) : nrows(rows), ncols(cols){
mat = new Row*[rows];
for(int i = 0; i < rows; i++) {
mat[i] = new Row(ncols);
for(int j = 0; j < ncols; j++){
// the operator-overload of Row[] isn't getting called and I don't get why not
mat[i][j] = value;
}
}
}
int main(){
Matrix m = new Matrix(2, 2, 4);
return 0;
Upvotes: 0
Views: 53
Reputation: 330
So I just figured it out myself.
I tried to call the []-operator from Matrix
through mat[][]
, but since mat
is a Row**
Row& Matrix::operator[](int i)
is never getting called.
Upvotes: 1
Reputation: 3551
mat[i]
gives you Row*
, and you want to call Row::operator[]
, but pointer to Row
is not dereferenced automatically. So you have to dereference it manually: (*mat[i])[j]
.
Upvotes: 1