Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can I not use the dummy parameter in postfix operator++ like someClassObject++5?

I know I can use a dummy int in the postfix operator++ as someClassObject.operator++(5), but why can't use it like someClassObject++5? I am asking this because operator+ can be used like someClassObject1 + someClassObject2.

{
public:

    test(int x, string y) : x(x), y(y){}
    test() :x(0), y("") {};

    //skiping some code for copy constructor and assignment operator overload

    test operator++(int x)
    {
        test a(*this);
        a.x += x;
        ++(*this);
        return a;
    }

    friend ostream& operator<<(ostream& ost, const test& test)
    {
        ost << test.x << " , " << test.y;
        return ost;
    }


    int x;
    string y;
};

int main()
{
    test t1(5, "testing");
    int x = 10;
    cout << t1.operator++(x) << endl;
    //the above line of code works but the line below gives error.
    t1++x;
    return 0;
}

I was expecting both t1.operator++(5) and t1++5 would work in the same way.

like image 994
TonyStark Avatar asked Jun 04 '19 08:06

TonyStark


People also ask

Why is a dummy parameter passed to the overloaded post increment operator?

You're not allowed to overload functions purely by return type, so a dummy parameter is necessary to differentiate between two identical looking operator++() operators.

What is a dummy parameter C++?

The dummy parameter is simply there to distinguish between the postfix and prefix operators. The name ++ or -- is the same in both cases, so there has to be some way to specify which one you're defining.

How does C++ compiler differentiate between overloaded postfix and prefix decrement 10 operators?

The compiler uses the int argument to distinguish between the prefix and postfix increment operators.

What is the purpose of the int parameter in the operator ++( Int function?

The int parameter is a dummy parameter used to differentiate between prefix and postfix versions of the operators. When the user-defined postfix operator is called, the value passed in that parameter is always zero, although it may be changed by calling the operator using function call notation (e.g., a.


1 Answers

Due to the maximal munch rule, the expression

t1++x

is parsed as

t1 ++ x

and grouped as

(t1 ++) x

This makes no sense; rather like t1 x makes no sense.

like image 156
Bathsheba Avatar answered Sep 20 '22 18:09

Bathsheba