Taimoor Mirza
Taimoor Mirza

Reputation: 1117

overloaded ++ operator isn't working in 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;
}

Upvotes: 6

Views: 1889

Answers (3)

Christophe
Christophe

Reputation: 73376

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.

Upvotes: 5

Ninda
Ninda

Reputation: 549

Here is both version prefix and post fix. And you can add some code in case of a call like c1++(1); (of course if needed)

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

circle& circle::operator++( int n ) {    //postfix version
    if( n != 0 )                // Handle case where an argument is passed.
       //some code
    else
        Area = Area * 2.0;       // Handle case where no argument is passed.
    return *this;
}


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

    system("pause");
    return 0;
}

Upvotes: 0

DimChtz
DimChtz

Reputation: 4333

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 );

Upvotes: 7

Related Questions