About the C++ overloaded operators

Viewed 80

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 known, the prefix ++ has higher precedence than binary *. But in the output shown above, the prefix ++ is called after the binary *! Is it because the compiler treats the operator+ as a function call (which leads to Unspecified Behavior)? Can I always consider an overloaded operator as a function (which makes the behavior of x = x++ well-defined when x is an Int)?

Thanks!

2 Answers
Related