About overloaded C ++ operators

Running the program below on my computer

#include <iostream>

class Int {
public:
  Int(int x) : val{x} {}
  Int operator++() {
    std::cout << "Int::operator++()\n";
    return ++val;
  }
  friend Int operator+(Int a, Int b) {
    std::cout << "operator+(Int, Int)\n";
    return a.val + b.val;
  }
  friend Int operator*(Int a, Int b) {
    std::cout << "operator*(Int, Int)\n";
    return a.val * b.val;
  }

private:
  int val;
};

int main()
{
  Int a = 1, b = 2;
  b = ++a + b * b;
  return 0;
}

      

I got this output:

operator*(Int, Int)
Int::operator++()
operator+(Int, Int)

      

As far as I know, the prefix ++

has a higher priority than the binary one *

. But in the example shown above, the prefix ++

is named after the binary *

! Is it because the compiler treats the + operator as a function call (which results in the Unspecified Behavior)? Can I always treat an overloaded operator as a function (what makes the behavior x = x++

correct when it x

is Int

)?

Thank!

+3


source to share


2 answers


Is this because the compiler treats operator+

both as a function call (which results in the Unspecified Behavior)?

Yes. But keep in mind that it doesn't matter if the ++a

after is evaluated b * b

, because in the end the two are added correctly, which follows the operator precedence rules.

Your unassigned expression is equivalent to:

operator+(a.operator++(), operator*(b, b))

      



The order in which the function arguments are evaluated is not specified, so it is technically ++a

possible to evaluate before b * b

, but also vice versa.

Can an overloaded operator always be treated as a function (which makes the behavior x = x++

correct when it x

is Int

)?

Yes and no. If Int

does the same thing as "normal" operators, then no (before C ++ 17), because that would be undefined behavior. But if it Int

doesn't change x

in x++

, for example, then yes.

+5


source


As far as I know, the prefix ++

has a higher priority than the binary one *

.



Higher priority does not mean that the prefix increment will be called before the multiplication operator, but in what order the parameters are bound to the corresponding operation.

+1


source







All Articles