Click here to Skip to main content
15,911,035 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
class Matrix
     {
      public:
             Matrix(float m11=0, float m12=0, float m21=0, float m22=0);
             Matrix(const Matrix &m);

             virtual ~Matrix() {delete[] d;};

             Matrix operator+(const Matrix &m) const;
             Matrix& operator=(const Matrix &m);

             float &c(int i, int j) const {return d[2*(i-1)+(j-1)];};

      private:
              float *d;
       };



class DiagonalMatrix : public Matrix
     {
      public:
            DiagonalMatrix() {};
            DiagonalMatrix(float d1, float d2) {c(1,1) = d1; c(2,2) = d2;};
     };




Matrix::Matrix(float m11, float m12, float m21, float m22)
      {
        d = new float[2*2];
        c(1,1)=m11; c(1,2)=m12; c(2,1)=m21; c(2,2)=m22;
       }

Matrix::Matrix(const Matrix &m)
       {
        d = new float[2*2];
        for (int i=0 ; i<2 ; i++)
        for (int j=0 ; j<2 ; j++)
        c(i,j) = m.c(i, j);
}




Matrix Matrix::operator+(const Matrix &q) const
{
Matrix r;

for (int i=1 ; i<=2 ; i++)
for (int j=1 ; j<=2 ; j++)
r.c(i,j) = c(i,j) += q.c(i,j);

return r;
}

Matrix& Matrix::operator=(const Matrix &q)
{
for (int i=1 ; i<=2 ; i++)
for (int j=1 ; j<=2 ; j++)
c(i,j) = q.c(i,j);

return *this;
}
C++

Posted

1 solution

From the first glance: it is already gone wrong. The bad idea is to derive a DiagonalMatrix from a Matrix. You see, normally a derived class is an extension of the base, override of part of it, or both. In contrast, a DiaginalMatrix is just a special case of matrix. It has exactly the same set of operation as other matrices. Don't derive it; instead, create a special constructor, or, better yes, a static factory method (say, Matrix Matrix::CreateDiagonalMatrix) creating a diagonal matrix.

—SA
 
Share this answer
 
Comments
Richard MacCutchan 4-Dec-11 3:51am    
+5, excellent advice again.
Sergey Alexandrovich Kryukov 4-Dec-11 10:00am    
Thank you, Richard. There can be other problems, but the general design things such as class hierarchy should be fixed first.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900