in the following code how does the compiler comes to know that it has to call the postfix function

class Digit
{
private:
    int m_nDigit;
public:
    Digit(int nDigit=0)
    {
        m_nDigit = nDigit;
    }

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

    Digit operator++(int); // postfix
    Digit operator--(int); // postfix

    int GetDigit() const { return m_nDigit; }
};

Digit& Digit::operator++()
{
    // If our number is already at 9, wrap around to 0
    if (m_nDigit == 9)
        m_nDigit = 0;
    // otherwise just increment to next number
    else
        ++m_nDigit;

    return *this;
}

Digit& Digit::operator--()
{
    // If our number is already at 0, wrap around to 9
    if (m_nDigit == 0)
        m_nDigit = 9;
    // otherwise just decrement to next number
    else
        --m_nDigit;

    return *this;
}

Digit Digit::operator++(int)
{
    // Create a temporary variable with our current digit
    Digit cResult(m_nDigit);

    // Use prefix operator to increment this digit
    ++(*this);             // apply operator

    // return temporary result
    return cResult;       // return saved state
}

Digit Digit::operator--(int)
{
    // Create a temporary variable with our current digit
    Digit cResult(m_nDigit);

    // Use prefix operator to increment this digit
    --(*this);             // apply operator

    // return temporary result
    return cResult;       // return saved state
}

int main()
{
    Digit cDigit(5);
    ++cDigit; // calls Digit::operator++();
    cDigit++; // calls Digit::operator++(int);

    return 0;
}

i know my doubt may is wierd but i m totally confused with the concept that compiler calls prefix func when we write ++ob and calls postfix func when we write ob++...how does compiler gets to know which func to call???does ob++ means we are calling operator++(int) fun ...if yes,then why???

The ++ operator doesn't know the difference, the compiler determines the difference based on where the ++ operator is used, such as ++i or i++. And in some cases it won't matter whether its post or prefix. The code inside the operator function should not care one way or the other.

sir but how does the compiler gets to know that if i m writing ob++ then it has to call the func operator++(int)...

In your example ob must be an int. For ob++ the ob int is evaluated first, then when that is done it calls the ++ operator (either the default c++ operator or the one in your program that you wrote).

based on the parameter passed in postfix,compiler internally treats as postfix

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.