Search code examples
c++matlabmatrixoverloadingoperator-precedence

Precedence order between overloaded operator and member function of the same class in c++


I am working on a matrix class in c++ to make matrix operations very similar to MATLAB. There are two types of multiplications available in MATLAB.

  1. '*' -> Matrix to matrix multiplication
  2. '.*' -> Element wise multiplication

To achieve these operations in c++, I have overloaded '*' operator to do Matrix to matrix multiplications and have provided a member function mult() to do element wise operations. However, I am not able to figure out what is the precedence order between the two. For example, I have three objects A with size (2x3), B with size (2x3) and C with size (3x2). Operations can be performed in following two major ways

  1. A.mult(B)*C
  2. C*A.mult(B)

I am throwing the exceptions from both the overloaded operator and the member functions. However, as this class is going to be used by the people who do not know much about exceptions handling, I would like to have mult() higher precedence than * if it is possible.

Let me know if I have broken any rules of stack overflow. I am a newbie and this is my first question.

Thanks in advance.


Solution

  • Function calls take precedence over the multiplication operator, as function calls have a precedence of 2, and multiplication has a precedence of 5, according to the C++ standard.

    See also : https://en.cppreference.com/w/cpp/language/operator_precedence