C ++ operator overloading and inheritance

So, I have a generic Matrix class that I created that has the following operational overload:

class Matrix { public: Matrix() {} Matrix(int i, int j, int k) {} Matrix operator*(const Matrix &right) { } }; 

I also have a Matrix2 class that inherits from my Matrix class.

 class Matrix2 : public Matrix { }; 

When I try to multiply two Matrix2 objects, I get a compiler error message:

'no operator was found that accepts a left operand of type Matrix2 (or there is no conversion available)'

Why is this and how can I correctly implement operator overloads with inheritance?

EDIT:

As stated, my problem was partly due to "the most unpleasant parsing." Now my problem, I believe, is strictly related to operator overloading and inheritance.

I can multiply two Matrix objects just fine, but I cannot combine two Matrix2 objects multiple times.

 Matrix2 i; Matrix2 m; Matrix result = m * i; 

Error message:

error C2678: binary '*' : no operator found which takes a left-hand operand of type 'Matrix2' (or there is no acceptable conversion).

+4
source share
3 answers

You bite the most cheeky analysis. This is a syntax error leading to the declaration of functions, not objects.

+3
source

The problem is not with the overloaded operator, but with the variables you specify, you probably think that m1 and m2 are of type Matrix , but in fact these are functions that return Matrix (without parameters). Try removing the parentheses in the ad and see if everything looks better.

This is Most Vexing Parse , which @DeadMG refers to in his answer.

+2
source

Check out this article on operator overloading that explains very well.

As @silvesthu explains, it would be better to implement the multiplication operator as a static function that takes 2 arguments and returns a new Matrix object. If you need to somehow change your class, for example, using the *= operator, you can implement this in terms of a static function.

Update

The following code works for me:

 class Matrix { public: Matrix() {} Matrix(int i, int j, int k) {} Matrix operator*(const Matrix &right) { return Matrix(); } }; class Matrix2 : public Matrix { }; int _tmain(int argc, _TCHAR* argv[]) { Matrix2 a, b; Matrix c = a * b; return 0; } 

It is shown that two Matrix2 objects can indeed be multiplied together. I am not sure why you are having any problems.

+2
source

All Articles