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();
}
Mohammad
  • 145
  • 8

1 Answers1

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

The Grand J
  • 348
  • 2
  • 5
  • 14
  • 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 Aug 03 '20 at 02:58
  • @Mohammad I just added my source so you can read up about it more – The Grand J Aug 03 '20 at 03:00
  • 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. – The Grand J Aug 03 '20 at 03:02
  • 1
    @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. – Nicol Bolas Aug 03 '20 at 03:03
  • Thanks @NicolBolas. I got the reason now. – Mohammad Aug 03 '20 at 05:18