1

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.

  • fiddling with some code that you found online will not help you learn the language, grab [a good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – skeller May 30 '19 at 19:29
  • public = everyone can access; protected = class and derived can access; private = access only within same class – skeller May 30 '19 at 19:32

1 Answers1

3

From access specifiers at cppreference.com

A private member of a class can only be accessed by the members and friends of that class, regardless of whether the members are on the same or different instances:

class S {
private:
    int n; // S::n is private
public:
    S() : n(10) {} // this->n is accessible in S::S
    S(const S& other) : n(other.n) {} // other.n is accessible in S::S
};
Amadeus
  • 10,199
  • 3
  • 25
  • 31
  • 1
    Thanks for the reply. It's been a while since I've actually worked with classes, so this is a nice refresher for me. Thanks for your answer. – BestQualityVacuum May 30 '19 at 19:41