As we know to differentiate between pre-increment & post-increment operator function, we use a dummy argument in post-increment operator function. But how the compiler INTERNALLY differentiate between these two functions as we know in function overloading, compiler differentiate multiple functions(of same name) by number of arguments passed(& the arguments is received by the function), but here we don't pass any argument while calling, but in argument of function definition we declare 'int'.
class Integer
{
int x;
public:
void setData(int a)
{ x = a; }
void showData()
{ cout<<"x="<<x; }
Integer operator++() // Pre increment
{
Integer i;
i.x = ++x;
return i;
}
Integer operator++(int) // Post increment
{
Integer i;
i.x = x++;
return i;
}
};
void main()
{
Integer i1,i2;
i1.setData(3);
i1.showData();
i2 = ++i1; // Calls Pre-increment operator function
i1.showData();
i2.showData();
i2 = i1++; // Calls Post-increment operator function
i1.showData();
i2.showData();
}
Another question, why i2 = i1++ calls post-increment function why not pre-increment one. Since we are not passing any value, how compiler calls only the postfix function. Is it predefined that 'dummy argument function' is used for post-fix function call only?
Also, can we pass other 'float', 'double' or other datatypes as dummy argument instead of only 'int'?
Only one argument is used as dummy or more than one?
Not sure if I understand the question. The compiler can distinguish them because they are two different operators.
x++is different from++x.Maybe it helps to consider that custom operators are just syntactic sugar for calling special methods that you can overload. For example if you have:
Then you can call the methods via
x++or++xor via the lengthy:And this is no different from the compiler deciding what method to call here: