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:
In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).
The Subscript or Array Index Operator is denoted by '[]'. This operator is generally used with arrays to retrieve and manipulate the array elements. This is a binary or n-ary operator and is represented in two parts: postfix/primary expression. expression.
The subscript operator is commutative. Therefore, the expressions array[index] and index[array] are guaranteed to be equivalent as long as the subscript operator is not overloaded (see Overloaded Operators). The first form is the most common coding practice, but either works.
Of the operators, only the function call operator and the operator new can have default arguments when they are overloaded.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With