0

I have a matrix class and I want to overload the * operator in c++ to multiply a scalar to the matrix.. I am able to achieve..

matrix1 * matrix2
matrix1 * 5

but I also want 5 * matrix1 to work.

How to achieve this.. Idk what to search for this, nothing is coming related :|

  • 1
    You'd likely benefit from reading [this answer to "What are the basic rules and idioms for operator overloading?"](https://stackoverflow.com/a/4421719/364696). Short version: The class implements `*=` as a member function, then you implement both directions in terms of it using non-member functions. – ShadowRanger May 21 '21 at 12:42

1 Answers1

2

Like this, calling your existing matrix * scalar function with the arguments reversed:

inline matrix operator*(int scalar, const matrix& mat) {
    return mat * scalar;
}

The above is a free function, to be declared in whatever namespace matrix is in, not inside the class.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436