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;
}
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 );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With