Steffen wrote:

is there a simple way to use operators overloaded in some class for

objects of a derived class?

In my example I have a class Matrix that represents 2x2 matrices, and I

overloaded operator= and operator+ for this class. Then there is a

derived class DiagonalMatrix which represents diagonal 2x2-matrices. Now

I would like to use the operators = and + also for the diagonal

matrices, but the naive way doesn't work:

matrix.cc: In function `int main()':

matrix.cc:83: error: no match for 'operator=' in 'D3 =

Matrix::operator+(const Matrix&) const((&D2))'

matrix.cc:22: error: candidates are: DiagonalMatrix&

DiagonalMatrix::operator=(const DiagonalMatrix&)

Is there a way to do this without redefining these operators in the

derived class?

It's generally a BAD IDEA(tm). First of all, your 'DiagonalMatrix' is not

necessarily properly derived. Think of this: a diagonal matrix has some

specific properties not all matrices have, right? Now, if I create some

algorithm that works on a "plain", unconstrained, Matrix, and then pass

a DiagonalMatrix to it, the algorithm can change the contents of my object

without concerning itself with the properties a diagonal matrix has, no?

It can simply add something off the main diagonal, and here you go, your

DiagonalMatrix object is not true any more.

So, whatever operation is performed by a member function of the base class

is not necessarily the right operation for the derived class, and that's

why you should think twice before allowing that.

But generally speaking, if you want to allow your operator+ that you wrote

for 'Matrix' to be used on a 'DiagonalMatrix', you will have to live with

the fact that it returns not a DiagonalMatrix, but only a Matrix. To make

it compile, define operator+ as NON-member. If you need it to be able to

access private data of Matrix objects, declare it a friend. That will

allow conversions (from DiagonalMatrix& to Matrix&) to be performed on

both operands, and not only on the right one.

V