c++datamember

Redundant Data Members


I have a class A which stores a SquareMatrix.

class A{
private:
    SquareMatrix mat;
};

The class frequently uses the size of the matrix using mat.size() (a constant time operation). mat.size() really is another measure of the size of A. Following good coding practice, should A also store a copy of mat.size()?

class A{
private:
    SquareMatrix mat;
    int size;
};

Solution

  • Storing a data member that represents the size of A in this example is not a good idea if "mat.size() really is another measure of the size of A".

    The primary issue here is: how is A::size supposed to keep track of changes to SquareMatrix::size()? This value can change in potentially many places, and keeping them both in sync will be tricky, and difficult to maintain even if you pull that off.

    Instead, provide a member function for A that simply returns the result of mat.size() like this:

    class A{
      private:
        SquareMatrix mat;
      public:    
        int size() const { return mat.size(); }  // mat.size() IS A's size :)
    };