c++operator-overloadingunary-operatorpostfix-operator

Does C++ compiler treat all postfix operator overloading as same (postfix version of - and --)?


#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- ?


Solution

  • 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);