Search code examples
c++c++11operator-overloadingoperator-keywordpostfix-operator

C++ overloading postfix operator


As per my understanding the effect of the overloaded postfix operator on a variable would be reflected in the next occurrence of the variable.

But the below program contradicts my understanding,

Please help me in understanding what is happening in the below program.

#include <iostream>

typedef struct Rectangle_Tag
{
    int len;
    int breadth;

}Rectangle_S;

/* Overloading an infix opertor */
Rectangle_S operator+(Rectangle_S a, Rectangle_S b)
{
    Rectangle_S c;

    c.len = a.len + b.len;
    c.breadth = a.breadth + b.breadth;

    return c;
}

/* Overloading a prefix opertor */
Rectangle_S operator++(Rectangle_S &a)
{
    a.len += 1;
    a.breadth += 1;

    return a;
}

/* Overloading a postfix opertor */
Rectangle_S operator++(Rectangle_S &a, int val)
{
    a.len += 1;
    a.breadth += 1;

    return a;
}

int main(void)
{
    Rectangle_S r1, r2, r3;

    r1.len = 20;
    r1.breadth = 10;

    r2.len = 20;
    r2.breadth = 10;

    r3 = (r1++) + (r2);

    std::cout << "\tr3.len     : " << r3.len << '\n';
    std::cout << "\tr3.breadth : " << r3.breadth << '\n';

    return (0);
}


//Expected Output :
    r3.len     : 40
    r3.breadth : 20

//Actual Output :
    r3.len     : 41
    r3.breadth : 21

Solution

  • Nobody's perfect!

    The author of the code has implemented the postfix operator in an idiosyncratic way. A correct way is

    Rectangle_S operator++(Rectangle_S &a, int)
    {
        auto old = a;
        ++a;
        return old;
    }
    

    Note too that the prefix ++ should return the modified object by reference.