ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Overloading postfix ++ and prefix ++ Operator with Example

Updated on June 14, 2016

1. Introduction

We know that a binary operator requires two operands in which it performs the operation. Say, for example, the addition operator adds two numbers and hence it requires two numbers and we call that two operands and the + that performs the addition operation as the PLUS operator. Now let us consider the number “-12”. Here the minus states the negation of the number and the negation operate on only one number. So we can say – as a unary operator.

In this Hub, we will see how to overload ++ unary operator in both prefix and postfix forms.

2. The Number Class

The class TheNumber shown below has two private integer members. The constructor with two integer parameter initializes the class private members. Print method of this class prints the private member values in the console output.

You can also see an overloaded binary plus operator in the implementation. The code for the TheNumber Class is shown below:

//Sample 01: A class that denotes two numbers (For Example only)
class TheNumber
{
private:
    int m_Number1;
    int m_Number2;
public:
    //Sample 02: Constructor
    TheNumber(int x, int y)
    {
        m_Number1 = x;
        m_Number2 = y;
    }

    //Sample 03: The print Method
    void print()
    {
        cout<<"m_Number1 ="<< m_Number1<<endl;
        cout<<"m_Number2 ="<<m_Number2<<endl;
    }

    //Sample 04: Overload Binary Operator +
    TheNumber operator+(TheNumber obj2)
    {
        int loc_Number1 = m_Number1 + obj2.m_Number1;
        int loc_Number2 = m_Number2 + obj2.m_Number2;
        return TheNumber(loc_Number1, loc_Number2);
    }
};

3. Overloading Prefix increment Operator ++

The prefix operator can be implemented the same way as we implemented the binary + operator. Note that the implementation does not take any parameter and the calling object itself serves the data for the first operand. Have a look at the below implementation:

//Sample 05: Overloaded Unary Prefix operator
TheNumber operator++()
{
    m_Number1 = m_Number1 + 1;
    m_Number2 = m_Number2 + 1;
    return *this;
}

In this implementation, we increment both the private members with a value of one. Once this is done, the current object is returned to the caller. Remember that the current object is the operand also. With this overloaded operator, you can use the prefix notation of increment on the object. For example, if the instance of the TheNumber is K, then we can use ++K, to increment both of the private members of the K.


Now have a look at the usage code shown below:

//Usage 01: The code that uses unary and binary operators
TheNumber num1(1,1);
TheNumber num2(1,1);

//Usage 02: Use the prefix increment operator
TheNumber num3 = ++num1 + ++num2;
num3.print();

In the above example, we created two number objects namely num1 and num2. In the usage02 code snippet, the prefix operator is applied on both the objects num1 and num2 before performing the addition operation. The calling sequence goes like this:

  1. First, the prefix increment for the number is called.
  2. Secondly, the prefix increment operator for the num2 object is called.
  3. Thirdly, the binary operator + is called on both the objects num1 and num2.

At step1, the private members for the num1 object are incremented and the object is returned. At step2, the private members for the num2 object are incremented and num2 is returned. In the third step, the incremented objects are added using overloaded binary operator plus. So you will see the result as shown below:

Source

The above process can be illustrated as follows:

Source

4. Overloading Postfix operator

The postfix operator can be overloaded slightly differently. First, the operator function requires a dummy integer parameter to differentiate this from the prefix overloaded operator. Next, in the implementation we clone the object, perform increment on the calling object i.e. at the operand one, and then return the cloned object. This way after the statement execution we see the increment taking in effect. Have a look at the below implementation:

//Sample 06: Overloaded Unary Postfix operator
TheNumber operator++(int dummyNo)
{
    TheNumber cloned = (*this);
    m_Number1 = m_Number1 + 1;
    m_Number2 = m_Number2 + 1;
    return cloned;
}

Note that the clone is done first. Then the increment is performed on the local object and the cloned copy is returned to the caller. So caller perspective, the expression in which the operator called gets only the cloned copy. After the statement execution is done we do see the increment take part in the operand. The parameter dummy is not doing anything here, right? This parameter is useful for the compiler to distinguish between prefix and postfix overload. Look at the below code that uses the Postfix operator:

//Usage 01: The code that uses unary and binary operators
TheNumber num1(1,1);
TheNumber num2(1,1);

//Usage 02: Use the postfix increment operator
TheNumber num4 = num1++ + num2++;
num4.print();

Here, postfix operator for num1 called first. Then postfix operator for the num2 is called. But the postfix operator on both the cases returned a cloned copy and those cloned copies are added together to get a result of 2 in the object num4. Note that we refer the num1 and num2 object after the expression evaluation you do see the increment in the internal members. The result of the above code is shown below:

Source

If you need more explanation, have a look at the below picture. In the postfix operator we make the changes on the real objects and but at the same time, we return the cloned copy which was taken before the change was applied to the real object. The binary plus operator actually operates on the cloned copies and hence we get the members with a value of two in the result object num4.

Source

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      MaskedBit 3 years ago

      There are a couple of fine details to pay attention to when implementing the postfix increment and decrement operators. First, the return type of the function should be const: "const TheNumber operator++(int) ..." Returning a non-const object allows statements like "myNum++++;", which will NOT increment myNum twice. The second detail is that, to ensure that the prefix and postfix forms perform the same increment, good practice calls for implementing the postfix form using the prefix operator. There's a thorough discussion of these details in Item 6 in "More Effective C++" by Scott Meyers. Even though it's a bit old now, it's still an invaluable reference for any C++ guru.

    • sirama profile image
      Author

      sirama 3 years ago

      Thanks for the information MaskedBit. It is useful.

    • tirelesstraveler profile image

      Judy Specht 3 years ago from California

      O.K. I didn't understand a thing outside of binary. My husband is the computer engineer and he speaks Unix and Linux and sometimes English.

    Click to Rate This Article