0

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++;
  • You might want to review [ask]. The title is supposed to be a summary. It should be comprehensible without additional context. (What is "line 19" supposed to mean to someone reading just the title?) The body is where you should expand upon the summary. Ideally, the gist of your question will be understood *before* reading any code. (A description of what is in line 19 would be more understandable than simply writing "line 19".) – JaMiT Oct 01 '21 at 05:42
  • 2
    What is it that you do not understand about "no 'operator++(int)' declared for postfix '++'"? You did not declare `operator++(int)` and yet you tried to use it. Why do you believe your code should work as-is (based upon your programming knowledge, not upon an archaic compiler)? – JaMiT Oct 01 '21 at 05:44
  • Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) in particular, the "Arithmetic Operators" section of the answer covering [Common operators to overload](https://stackoverflow.com/questions/4421706/operator-overloading-in-c/4421719#4421719). – JaMiT Oct 01 '21 at 05:46

1 Answers1

0

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.

Chris Uzdavinis
  • 6,022
  • 9
  • 16