I'm writing up some code as part of a little project I'm working on, and something stood out to me as I was testing my code. I'm working with a class function shown below:
class Matrix{
public:
//Constructors
Matrix(); //EMPTY Matrix
Matrix(int, int); //Matrix WITH ROW AND COL
Matrix(const Matrix &); //Copy a matrix to this one
~Matrix(); //Destructor
//Matrix operations involving the matrix in question
Matrix madd(Matrix const &m) const; // Matrix addition
private:
double **array; //vector<vector<double>> array;
int nrows;
int ncols;
int ncell;
};
Below, paying attention to the madd function, I've written it out in another file shown below:
Matrix Matrix::madd(Matrix const &m) const{
assert(nrows==m.nrows && ncols==m.ncols);
Matrix result(nrows,ncols);
int i,j;
for (i=0 ; i<nrows ; i++)
for (j=0 ; j<ncols ; j++)
result.array[i][j] = array[i][j] + m.array[i][j];
return result;
}
I suppose you can guess that it does matrix addition. To be honest, I found some code online, and I'm just trying to modify it for my own use, so this function wasn't completely written by me. I managed to compile this, and after a small test, it worked correctly, but what I'm confused by is how in the function I was able to call m.ncols and m.nrows. Looking at the class definition, the members are private, so how am I allowed to access them? Even though the argument m is passed as a const, since the nrows and ncols parameters are protected, shouldn't I NOT be able to access them (from the argument)? I'm confused as to why this is allowed.