4
#include <cstdio> #include <iostream> using namespace std; class Int32 { int num; public: Int32(int num = 0) : num(num) {} ~Int32() {} int value() { return num; } Int32 & operator - (int x) { cout << "Postfix of -" << endl; return *this; } Int32 & operator -- (int x) { cout << "Postfix of --" << endl; return *this; } }; int main() { Int32 x(100); x--; x-; // [Error] expected primary-expression before ';' token x.operator-(0); return 0; } 

From the above code I overloaded postfix increment and postfix unary minus. I know postfix unary minus doesn't make sense, but I wonder why I have compilation error for x- and don't have any issue with x-- and x.operator-(0) operations.

I compiled this code in DevC++ and I got following error.

[Error] expected primary-expression before ';' token 

What is wrong with x- ?

5
  • x- doesn't exist. where you use this operator? there will be only unary minus. Commented Aug 8, 2020 at 16:48
  • 1
    @Sanjeev: His point is that the compiler lets him declare a function that is a postfix unary minus operator, and he can even call it, but he can't use the operator syntax. Commented Aug 8, 2020 at 16:49
  • 3
    Parsing is done independently of overload resolution. x-; fails because the language grammar doesn't allow it. Commented Aug 8, 2020 at 16:50
  • 1
    You can define the function because you can call it using the x.operator-() syntax. Commented Aug 8, 2020 at 16:51
  • 1
    That's not a "unary postfix - operator", it's a "binary infix - operator". Commented Aug 8, 2020 at 17:17

1 Answer 1

2

What is wrong with x- ?

Nothing wrong with it; This by language design. You will see the same error with

1 - ; 

meaning, the operator - expect an argument to work with like you did it in the next line

x.operator-(0); 
Sign up to request clarification or add additional context in comments.

2 Comments

x--; also expecting one argument and implicitly ZERO has passed. I am expecting same for x-;. As @Barmer said, parsing is done independently of overload resolution. Does not mean it I can use any operator syntax to call Int32 & operator - (int x)?
@vinothkumar That is for x - 0 (or any Int32{} - int{})

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.