Search code examples
c++operator-overloadingoperatorslanguage-lawyerdefault-arguments

Provide default arguments for subscript operator and function call operator


In the following code, I have provided default arguments for array subscript operator.

struct st 
{
    int operator[](int x = 0)
    {
        // code here
    }
};

But, compiler generated an error :

error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)

But, If I provide default arguments for function call operator.

struct st 
{
    int operator()(int x = 0)
    {
        // code here
    }
};

It's working fine.

So, I have a questions:

  • Why doesn't allowed default arguments for the array subscript operator?
  • Why does allowed default arguments for the function call operator?

Solution

  • The standard states it quite clearly.

    The default arguments are not allowed in operator overloading of subscripting operator.

    An operator function cannot have default arguments, except where explicitly stated below. Operator functions cannot have more or fewer parameters than the number required for the corresponding operator, as described in the rest of this subclause.

    and

    operator[] shall be a non-static member function with exactly one parameter.

    While for function call operator

    operator() shall be a non-static member function with an arbitrary number of parameters. It can have default arguments.

    Overloaded operators try to follow the same behavior of the built-in ones; with the built-in subscript operator the (only one) index is always required, it doesn't have default arguments. Then the overloaded operator is not allowed to have default arguments either. On the other hand, functions are always fine to take arbitrary number of parameters and have default arguments.