Home > Blockchain >  Overloading a function by return type?
Overloading a function by return type?

Time:12-08

One of the most viewed questions here on SO is the question that deals with overloading of various operators. There is something I don't understand about the overloading of brackets operator operator[]. My question is about the following code:

class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
  // ...
};

Here the operator is overloaded twice, one function which allows the change of members and one which does not. I read that c doesn't allow function overloading by return type, but this looks like it. T& is changed to const T&. Can someone explain to me what exactly is this "overloading" called and why does this work?

Thanks in advance.

PS: If this works because the second const keyword changes the "invisible" this pointer argument to const this then I understand, but still, is there a name for that practice?

CodePudding user response:

For overloading to work the functions need to have different signatures (the return type does not count).

In methods the this pointer to the object also counts as an implicit (first) argument. Static methods of course don't have a this pointer, so they can be treated like global functions.

In your example the two methods have different arguments. idx is identical in both cases but the first method has a this pointer of type X*, which is a variable pointer. In the second method the this pointer is a constant type: const X* and is thus distinct from the first one, that's why the overloading works.

The return value is inconsequential to the overloading. If only the return values were different, overloading would not have been allowed by the compiler.

class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
                     // -----------------------^^^^^
                     // This is what makes the overloading possible.
};
  • Related