I was trying to make virtual operator on C++
class Data
{
virtual Matrix operator* (Matrix &_matrix);
virtual Scalar operator* (Scalar &_scalar);
};
class Matrix : public Data
{
private:
vector<vector<double>> data;
public:
// ...
Matrix operator* (Matrix &_matrix);
};
class Scalar : public Data
{
private:
double data;
public:
// ...
Scalar operator* (Scalar &_scalar);
};
And the problem was, when I created Data* Array like below
Data* arr[10];
arr[0] = new Matrix(3,3);
arr[1] = new Matrix(3,3);
arr[0]->operator*(arr[1]);
I could not do multiplication between these two matrices, since I cannot pass Data as an argument.
But the problem is, I cannot make the function’s argument to take Data* type because, it will not be able to access private members of Matrix or Scalar objects.
How to deal with this kind of weird situation?
Class double dispatch problem – See Meyer’s (forget which one).
You need the operator to be virtual on both the lhs and rhs, so you need two virtual calls:
I’ve glossed over the issue of the return type and memory management. As usual with operators, you might be better defining
*=as the primitive. This can then return a reference to*this. The*operator can then defined in terms of*=. Once again, this is in “Effective C++”.