-6

I am new to C++ and currently learning operator overloading of postfix operators, Here in the below program if i use one argument i am getting the result fine but if i go with two arguments the program is displaying incorrect output. I request the people to solve my issue and clear my doubt.

#include<iostream>
using namespace std;
class num
{
int a;
public:
num(int _a = 0)
{
    a = _a;
}
num operator ++ ()
{
    return a++;
}
num operator ++ (int)
{
    return (a++);
}

void show()
{
    cout << a << endl;
}
};

/*
class num
{
int a, b;
public:
num(int _a = 0, int _b = 0)
{
    a = _a;
    b = _b;
}

num operator ++ ()
{
    a++;
    b++;
    return *this;
}

num operator ++ (int)
{
    a++;
    b++;
    return *this;
}

void show()
{
    cout << a << b << endl;
}
};

*/
int main()
{
num ob(10);
num z,y;
ob.show();
z = ob++;
z.show();

y = ++ob;
y.show();
getchar();
return 0;
}

The commented code i used to increment two numbers using postfix operator. There is some problem with that code i am getting incorrect results.

arahan sharma
  • 79
  • 1
  • 3
  • 1
    Please define "incorrect results." When asking about program behaviour/output, always post both the expected and the actual output/behaviour. – Angew is no longer proud of SO Jan 20 '15 at 14:23
  • http://en.cppreference.com/w/cpp/language/operators and http://stackoverflow.com/questions/4421706/operator-overloading – sehe Jan 20 '15 at 14:27
  • do you expect `return a++;` and `return (a++);` to return different results? – BeyelerStudios Jan 20 '15 at 14:35
  • You can learn the difference between `++foo` and `foo++` here : http://www.parashift.com/c++-faq/increment-pre-post-overloading.html – NathanOliver Jan 20 '15 at 14:37
  • For future references: "_I request the people to solve my issue and clear my doubt_" isn't the right form to ask for help. Make sure to ask politely for an answer and you'll have a lot more chances to receive good solutions. – Marco A. Jan 20 '15 at 18:58

2 Answers2

2

In both cases, you're returning a copy of the object after incrementing it (or before, in the uncommented code at the start). The postfix operator should return a copy if the object before incrementing it. You could implement this in terms of the prefix operator:

num copy = *this;
++(*this);
return copy;
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

Copy first, then send copy.

 #include<iostream>
 using namespace std;
 class num
 {
    int a;
    public:
    num(int _a = 0)
    {
        a = _a;
    }
    num operator++ ()
    {
        num t=(*this);
        (this->a)++;
        return t;
    }
    num operator++ (int)
    {
        a++;
        return (*this);
    }

    void show()
    {
        cout << a << endl;
    }
};


int main()
{
    num ob(10);
    num z,y;
    ob.show();
    z = ob++;
    z.show();

    y = ++ob;
    y.show();
    getchar();
    return 0;
}
oknsnl
  • 351
  • 1
  • 11