Home > Software engineering >  How does the syntax for overloading post-increment operator in c work?
How does the syntax for overloading post-increment operator in c work?

Time:11-05

int operator  (int){
  //relevant code
}

I dont seem to understand the workings of the code for overloading post increment operator given above

I know that the int as a dummy parameter is given to differentiate between pre-increment and post increment operator overloading.

If a is a object of the class in which these operators are overloaded ,both a and a should have a equivalent representation as a.operator ()(as per my understanding ),how does the int parameter help in resolving it as a post increment operator?

-A c beginner

CodePudding user response:

If a is a object of the class in which these operators are overloaded ,both a and a should have a equivalent representation as a.operator ()(as per my understanding ),how does the int parameter help in resolving it as a post increment operator?

The post increment operator can be called with a dummy int argument but normally this isn't what you would do. In the following, typically you would define void foo::operator (int) so that you can make a call like (1) but (2) is legal.

#include<iostream>

struct foo {

    void operator  () {
        std::cout << "pre\n";
    }

    void operator  (int) {
        std::cout << "post\n";
    }
};

int main() {
    foo a;

    // these yield: pre
      a;
    a.operator  ();

    // these yield post:
    a  ;                  // (1)
    a.operator  (int{});  // (2)
}

CodePudding user response:

When the compiler sees a, and a is not a built-in type, then the compiler looks for either a::operator () or operator (a&) and if found then calls it.

When the compiler sees a , and a is not a built-in type, then the compiler looks for either a::operator (int) or operator (a&, int) and if found then calls it.

See Increment/decrement operators on cppreference.com for more details.

  •  Tags:  
  • c
  • Related