Search code examples
c++ooppolymorphismoperator-overloadingunary-operator

A simple operator overloading program in C++ on codeblocks. Got an error at line 19. The same program runs perfectly on Turbo C++


Got an error on line 19: error : no 'operator++(int)' declared for postfix '++' [-fpermissive]

#include<bits/stdc++.h>
using namespace std;
class sample
{
    int x,y;
public:
    sample(){x=y=0;}
    void display()
    {
        cout<<endl<<"x="<<x<<" and y= "<<y;
    }
    void operator ++(){x++;y++;}
};

int main()
{
    sample s1;
    sample s2;
    s1++;
    ++s2;
    ++s1;
    s1.display();
    s2.display();
    return 0;
}

Error on code line:

s1++;

Solution

  • TURBO C++? Haven't heard that name in a LONG time. That is a compiler from an era before C++ was even standardized, and is not representative of C++ anymore.

    Prefix increment and post-increment are different functions. You can't just overload one and expect both to work.

    Also your signature is wrong. It should return a type matching the class it's called on. For example:

    class sample
    {
    public:
    ...
        // prefix
        sample & operator ++()  {x++; y++; return *this; }
    
        // postfix (the int is a dummy just to differentiate the signature)
        sample operator ++(int) {
            sample copy(*this); 
            x++; y++; 
            return copy;
        }
    };
    

    The value of the return type is the main difference between the two so it's pointless for your operator to return void. One returns a reference, since it represents the incremented object, while the postfix version returns a copy that is the state of the pre-incremented object.