I have a couple of pure virtual classes, Matrix
and Vector
. Throughout my code base I try to only create dependencies on them and not their concrete subclasses e.g. SimpleTransformationMatrix44
and SimpleTranslationVector4
. The motivation for this is that I can use third party (adapted) classes in place of mine without much trouble.
I would like to overload the arithmetic operators (sourced from here):
T T::operator +(const T& b) const;
T T::operator -(const T& b) const;
T T::operator *(const T& b) const;
I want to declare them in the pure virtual classes so that it is valid to perform the operations on references/pointers to them, the problem being that an abstract class cannot be returned by value. The best solution I can think of is something like this:
std::unique_ptr<T> T::operator +(const T& b) const;
std::unique_ptr<T> T::operator -(const T& b) const;
std::unique_ptr<T> T::operator *(const T& b) const;
Which allows this (without down casts!):
std::unique_ptr<Matrix> exampleFunction(const Matrix& matrix1, const Matrix& matrix2)
{
std::unique_ptr<Matrix> product = matrix1 * matrix2;
return std::move(product);
}
A pointer seems to be the only option in this case since returning a value is invalid and returning a reference is just plain silly.
So I guess my question is: Have I gone off the plot with this idea? If you saw it in some code you were working on would you be thinking WTF to yourself? Is there a better way to achieve this?