0

I have this piece of C++ code to overload the pre-increment and post-increment operators. The only difference between those methods is the number of their arguments.

I want to know how C++ understands which method (pre-increment or post-increment) it should call when running y=++x and z=x++ commands.

class location { private: int longitude, latitude; public: location(int lg = 0, int lt = 0) { longitude = lg; latitude = lt; } void show() { cout << longitude << "," << latitude << endl; } location operator++(); // pre-increment location operator++(int); // post-increment }; // pre-increment location location::operator++() { // z = ++x; longitude++; latitude++; return *this; } // post-increment location location::operator++(int) { // z = x++; location temp = *this; longitude++; latitude++; return temp; } int main() { location x(10, 20), y, z; cout << "x = "; x.show(); ++x; cout << "(++x) -> x = "; x.show(); y = ++x; cout << "(y = ++x) -> y = "; y.show(); cout << "(y = ++x) -> x = "; x.show(); z = x++; cout << "(z = x++) -> z = "; z.show(); cout << "(z = x++) -> x = "; x.show(); } 
0

1 Answer 1

1

Essentially missing the argument in the ++ overload tells c++ that you are creating a prefix overload.

Including the argument tells c++ that you are overloading the postfix operator. therefore when you run ++x it will run the prefix while x++ will run postfix.

Also might i add that the int in the argument is not an integer datatype.

if you want more understanding then this is where I found the information: https://www.programiz.com/cpp-programming/increment-decrement-operator-overloading

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer. But still I'm not convinced. Neither of ++x nor x++ need an argument. So still I'm not sure how C++ distinguishes while calling those methods.
@Mohammad I just added my source so you can read up about it more
But essentially the int is not actually an argument. It is an indicator to c++ that you are using a postfix. Sorry if what I wrote didn't convey that.
@Mohammad: It works because the C++ language says that it works. The C++ language says that it transforms the call to ++x into a call to the one with no arguments. The C++ language says that it transforms the call to x++ into a call to the one with a single argument of type int. That's how it works.
Thanks @NicolBolas. I got the reason now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.