Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloaded ++ operator isn't working in c++

Tags:

c++

Can someone explain to me why my overloaded ++ (pre version) isn't updating the value? Snippet is like this:

circle circle:: operator++()
{  
    Area = Area * 2.0;
    return *this; 
}
/////////////////////////////

int main()
{
    class circle c1(4, 1, -1), c2(12, 4, 6);
    c1.output();
    c1++;
    c1.output();

    system("pause");
    return 0;
}
like image 210
TAM Avatar asked Mar 23 '16 11:03

TAM


2 Answers

It's because you overload the prefix and call the postfix. You need to call ++c1;. To use c1++; you need to overload the postfix as well:

  circle operator++ ( int );
like image 171
DimChtz Avatar answered Sep 30 '22 21:09

DimChtz


The signature of your overload operator should be:

circle& operator++();   // return by reference and this is prefix. 

But you use postfix, so it should be:

circle operator++ (int);   // int is unused

Changing the signature is not enough because you implement a prefix logic, directly changing the value without saving the initial value. So if you'd use postfix operator with your implementation in a combined expression like (c++).output(), it would not respect the expected semantic.

Here the implemetnation of both version:

circle& operator++ () {  // prefix
    Area = Area * 2.0;   // you can change directly the value
    cout << "prefix"<<endl; 
    return *this;        // and return the object which contains new value
}

circle operator++ (int) {  // postfix
    circle c(*this);     // you must save current state 
    Area = Area * 2.0;   // then you update the object 
    cout << "postfix"<<endl; 
    return c;            // then you have to return the value before the operation 
}

And here an online demo to show difference between both.

like image 32
Christophe Avatar answered Sep 30 '22 19:09

Christophe