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?
For starters the pre-increment operator should be declared and defined like
In these statements
there is explicitly visible which operator is called that is whether the unary increment operator
or the postfix increment operator
So the compiler does not have a problem to parse these statements and to select the appropriate function.
As for the last your question then for example according to the C++ 14 Standard (13.5.7 Increment and decrement)
To distinguish the unary increment operator from the postfix increment operator when they are called explicitly you need to specify for the postfix increment operator an argument equal to 0.
For example