Search code examples
c++syntaxlanguage-lawyerpostfix-operatorprefix-operator

overloading postfix and prefix operators


Please consider the following code:

#include <iostream>

using namespace std;
class Digit 
{
private: 
    int m_digit;
public: 
    Digit(int ndigit = 0) {
        m_digit = ndigit;
    }
    Digit& operator++(); // prefix
    Digit& operator--(); // prefix
    Digit operator++(int);
    Digit operator--(int);
    int get() const {
        return m_digit;
    }
};
Digit& Digit::operator++() {
    ++m_digit;
    return *this;
}
Digit& Digit::operator--() {
    --m_digit;
    return *this;
}
Digit Digit::operator++(int) {
    Digit cresult(m_digit);
    ++(*this);
    return cresult;
}
Digit Digit::operator--(int) {
    Digit cresult(m_digit);
    --(*this);
    return cresult;
}
int main() {
    Digit cDigit(5);
    ++cDigit;
    cDigit++;
    cout << cDigit.get() << endl;
    cout << cDigit.get() << endl;
    return 0;
}

Here are two versions of postfix and prefix operators implemented, I read that the difference is made by introducing another so-called dummy argument, but I have a question.

If we look at the declaration of these operators,

    Digit& operator++(); // prefix
    Digit& operator--(); // prefix
    Digit operator++(int);
    Digit operator--(int);

they differ by the & character, so why is a dummy argument necessary? Also, in both cases the operator ++ precedes the argument, and doesn't that suggest that the same thing is meant?


Solution

  • The pre- and post-increment are two distinct operators, and require separate overloads.

    C++ doesn't allow overloading solely on return type, so having different return types as in your example wouldn't be sufficient to disambiguate the two methods.

    The dummy argument is the mechanism that the designer of C++ chose for the disambiguation.