-1
#include <iostream>
using namespace std;

class B{
        int temp1;
    public :
        void disp()
        {   
        cout <<temp1;
        }
        void setA(int a)
        {
            temp1=a;
        }       
        void operator ++(int)
        {
            temp1+=5;
        }
        void cal()
        {
            temp1 ++;
        }
        };  

int main()
{
    B b; 
    b.setA(10);

    b.cal();
    b.disp();
    return 0;
}

I recently learned about operator overloading so playing around with code .....so the expected answer here is 15 but it is appearing as 11. Why is my overloaded operator not working...and specifically what is wrong with this code rsince there seems to be a logical error in this part:

void operator ++(int)
        {
            temp1+=5;
        }
        void cal()
        {
            temp1 ++;
        }
piku_baba
  • 59
  • 7
  • `temp1` is an int, not a `B`. – tkausl Mar 31 '19 at 19:26
  • What do you expect to happen here: `int temp1=10; temp1++;`. Why would the result be any different with your class, then? P.S. That's not really how the post-increment overload is supposed to work, but that's another issue. – Sam Varshavchik Mar 31 '19 at 19:26

1 Answers1

2

Note you overloaded the ++ operator for class B. The cal method increments using ++ the memeber temp1 which is an int, not a B - hence - it is increased normally, from 10 to 11.

If you would have done b++ in your main function you would have gotten what you expected. Note ++ should return the previous value of the incremented object, if you wish to remain conformal with expectations of most people, so

something = b++; //something should probably be a B. 

would work.

kabanus
  • 24,623
  • 6
  • 41
  • 74
  • so what you are saying here is that since this function `void operator ++(int)` can only be called by the object and doing `temp1++` means essentially object not calling but and 'int' calling the '++' operator so it would work in the orignal way for the int temp1....is that right? – piku_baba Mar 31 '19 at 19:48
  • @AnasAziz Exactly. – kabanus Mar 31 '19 at 19:49