Question

I have two classes, a Matrix, and then a Diagonal Matrix that inherits from the Matrix class.

Obviously, converting from Diagonal to Matrix is easy, but converting back requires a conversion.

class Diagonal : public Matrix<T>
{  
  operator Matrix<T>() const;
};

Exists in my code, which I thought should convert. In main, I have:

  Matrix<float> theMatrix(size,size);
  Diagonal<float> theDiag(size,size);
  theDiag = theMatrix;

Everything runs fine except the conversion, which tells me:

 no known conversion for argument 1 from ‘Matrix<float>’ to ‘const Diagonal<float>&’

Any suggestions? Thanks.

Was it helpful?

Solution

Your code

class Diagonal : public Matrix<T>
{  
  operator Matrix<T>() const;
};

defines a conversion from Diagonal<T> to Matrix<T>, whereas your assignment expects a conversion from Matrix<T> to Diagonal<T>.

Did you mean to write this instead?

class Matrix<T>
{  
  operator Diagonal<T>() const;
};

Now even if this works* (which I doubt, since it will cause a cyclic dependency), I'm not sure if it makes sense from a semantic perspective. Not every matrix is a diagonal matrix, so converting from a matrix into a diagonal matrix cannot preserve all data. Using implicit conversions for this situation is a bad idea from a design perspective.

*An alternative would be to define operator=(const Matrix<T>&) for Diagonal<T>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top