-1

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
user207421
  • 305,947
  • 44
  • 307
  • 483
SRIKANTH
  • 65
  • 7
  • 1
    Your prefix and postfix operator do the same thing so you'll get the same results. To see how it is done correctly see the section *Unary arithmetic operators* [here](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – NathanOliver Sep 12 '19 at 13:37
  • 2
    *"overloaded postfix operator on a variable would be reflected in the next occurrence"* It doesn't do that automagically. You need to implement this behavior manually. – HolyBlackCat Sep 12 '19 at 13:39
  • Whereas operators have specific meaning for built-in or standard type, user custom types might implement mostly how they want. To follow least surprise principle, it is better to follow built-in behaviors. Here, neither your `operator++` follows that principle. – Jarod42 Sep 12 '19 at 13:47

1 Answers1

3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483