Search code examples
c++overloadingoperator-keyword

How to add rhs value to class in C++ (operator overloading)


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 :|


Solution

  • 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.