ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Overloading "postfix ++" and "prefix ++" Operator in C++ with Example

Updated on May 10, 2018

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

    • tirelesstraveler profile image

      Judy Specht 

      4 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.

    • sirama profile imageAUTHOR

      sirama 

      4 years ago

      Thanks for the information MaskedBit. It is useful.

    • profile image

      MaskedBit 

      4 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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)