Operator overloading in combination with inheritance

Hello,

I've build a Matrix class with several methods and also several overloaded operators.

Next, I've created a Vector class which inherits from Matrix. This is nothing special, only rows = 1 and columns is an argument for the constructor which calls the constructor Matrix(int rows, int cols).

Next, I've created a SpaceVector (inherits from Vector) which has the form [x, y, z]. The only special thing about this class is that the constructor creates a Vector where columns = 3.

All the operators are declared public in the Matrix class, they are usable for the Vector class but not for the SpaceVector class.

Is there a way I can reuse my operators without reimplementing them on a lower level in the hierarchy ?

(sv1 and sv2 defined as SpaceVector)
This works:
Matrix m = sv1 + sv2;

but what I would want is:
SpaceVector sv3 = sv1 + sv2;
Last edited on
Operator overloading and inheritance don't mesh well for exactly this reason. You have to write wrappers
in the derived classes because you need the operators to return references to the most derived type, not
to a base class type.
That's what I thought.
I couldn't find any reference of how to do this in any of my books nor the internet.
Though everywhere I look, they say operator overloading is in its purest form basicly method overloading.

Thank you for your quick response.
You could get creative with templates...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <typename childclass>
class OperatorBase
{
public:
  childclass operator + (const childclass& rhs) const
  {
    const childclass& lhs = static_cast<const childclass&>(*this);

    // do common '+' code here
    // return a type of 'childclass'
  }
};

//----------

class Matrix
  : public CommonParentClass   // <--- good for inheritance, bad for generating operators
  , public OperatorBase<Matrix>  // <---- good for generating the operators, bad for inheritance
{
  //...
};
Topic archived. No new replies allowed.