I'm looking for advice as to how to proceed with this class hierarchy I'm building in C++.
Base class is Matrix:
class Matrix
{
protected:
int rows;
int columns;
double* values;
public:
\\lots of stuff goes here. bla di bla di bla.
virtual Matrix operator+(const Matrix& addend) const;
\\etc.
}
Squarematrix is inherited from Matrix
class Squarematrix : public Matrix
{
public:
Squarematrix operator+(const Squarematrix& addend) const;
}
Operator+ returns a matrix or a squarematrix respectively. Since operator+ is a virtual function this wont compile, as it must have the same return type in all classes.
So what are my options?
I could use an ordinary function instead of virtual. This is a bit annoying, but wouldn't cause a problem under most circumstances.
I could return a matrix in all cases. This would basically make my squarematrix class a right pain in the *** to use, as I would have to constantly downcast from matrix to squarematrix.
I could return a reference to a squarematrix. Then the matrix would have to be stored on the heap and there's no way to make sure its deleted safely. Especially if I do something like this:
squarematrix a=b+(c+d);
(c+d) will be stored on the heap and have no pointer to it so will be leaked.
Is there any way to keep virtual functions and still have different return types?
What would you advise in this situation?
Thanks for your help. Looking forward to hearing from you.