Software & Finance





C++ - Preincrement and Postincrement operator overloading





We can overload both preincrement and postincrement operators in C++. We need to pass a dummy argument int to specify that it is post increment. The same logic applies to pre decrement and post decrement operators also.

Here is the sample code:

class MyIncrDecrClass

{

public:

    int m_nCounter;

 

public:

    MyIncrDecrClass() : m_nCounter(0)

    {

    }

 

    // The following operator++() represents overloading of pre-increment

    MyIncrDecrClass& operator++()

    {

        ++this->m_nCounter;

        return *this;

    }

 

    // Passing dummy int argument is to mention overloading of post-increment

    MyIncrDecrClass& operator++(int)

    {

        this->m_nCounter++;

        return *this;

    }

 

    // The following operator--() represents overloading of pre-decrement

    MyIncrDecrClass& operator--()

    {

        --this->m_nCounter;

        return *this;

    }

 

    // Passing dummy int argument is to mention overloading of post-decrement

    MyIncrDecrClass& operator--(int)

    {

        this->m_nCounter--;

        return *this;

    }

};

 

void main()

{

    MyIncrDecrClass counter;

    counter++; // calls post increment operator function

    ++counter; // calls pre increment operator function

    counter--; // calls post decrement operator function

    --counter; // calls pre decrement operator function

}