Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator ++ [duplicate]

Class declaration:

class unaryOperators 
{
    public:
        int i;

        unaryOperators (int tempI = 0)
        {
            i = tempI;
        }

        unaryOperators operator++ (int);
        unaryOperators operator++ ();
};

Does this global definition correspond to postfix or prefix version of the overloaded operator++? Why?

unaryOperators operator++ (unaryOperators &one)
{   
    return one; 
}
like image 761
Aquarius_Girl Avatar asked Nov 30 '25 09:11

Aquarius_Girl


1 Answers

unaryOperators& operator++ (unaryOperators &one)
              ^^

is the non-member prefix unary increment operator.

The non-member postfix unary increment operator takes an additional int as an policy enforcing parameter.

unaryOperators operator++ (unaryOperators &one, int)

Reference:

C++03 Standard 13.5.7 Increment and decrement [over.inc]

The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a member function with no parameters, or a non-member function with one parameter of class or enumeration type, it defines the prefix increment operator ++ for objects of that type. If the function is a member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type. When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.125)

[Example:
class X {
   public:
      X& operator++(); // prefix ++a
      X operator++(int); // postfix a++
};
class Y { };
Y& operator++(Y&); // prefix ++b
Y operator++(Y&, int); // postfix b++

void f(X a, Y b) {
++a; // a.operator++();
a++; // a.operator++(0);
++b; // operator++(b);
b++; // operator++(b, 0);
a.operator++(); // explicit call: like ++a;
a.operator++(0); // explicit call: like a++;
operator++(b); //explicit call: like ++b;
operator++(b, 0); // explicit call: like b++;
}
—end example]
like image 87
Alok Save Avatar answered Dec 03 '25 00:12

Alok Save