Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to implement an operator in a derived class using the same operator that is already implemented in the base class?

Given these classes:

class Matrix{
//...
public:
   Matrix(int row, int column) {
     ...
   };
   Matrix operator+(const Matrix &matrix) const{
   ...
   }
};
class MatrixSquare : public Matrix{
//...
public:
   MatrixSquare(int size) {
     ...
   };
   MatrixSquare operator+(const MatrixSquare &matrix) const{
     ??????
   }
};

I’m trying to implement MatrixSquare operator+ by using Matrix::operator+. But Matrix::operator+ returns Matrix.

Do I have to create the copy constructor MatrixSquare(const Matrix &matrix) ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the recurring template pattern and don’t need to implement the operator in the child

template <typename Child>
class Matrix {
//...
public:
   Matrix(int row, int column) {
     ...
   }
   Child operator+(const Child &matrix) const {
   ...
   }
};

class MatrixSquare : public Matrix<MatrixSquare> {
//...
public:
   MatrixSquare(int size) : Matrix(size, size) {
     ...
   }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading