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) ?
>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) {
...
}
};